搭建好Spring MVC基本配置后 做上传文件
1. 在springmvc 配置文件中配置文件上传
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- set the max upload size100MB -->
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>
2. 写一个简单的JSP页面
<form action="bookinfo/upload.action" enctype="multipart/form-data" method="post">
编号:<input type="text" name="bookid"/><br/>
名称:<input type="text" name="bookname"/><br/>
价格:<input type="text" name="bookprice"/><br/>
上传图片:<input type="file" name="bookimg1"/><br/>
<input type="submit" value="添加新书"/><br/>
</form>
需要注意的几点
1. method = "post" ,不能用get 因为get传输的数据上限只有1K
2. enctype="multipart/form-data" 不能忘记加上
3. 在自己写的controller层写上传方法
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(HttpServletRequest req, Bookinfo bookinfo) throws Exception {
//重写request方法
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
//得到图片
MultipartFile file = mreq.getFile("bookimg1");
//得到图片名字
String fileName = file.getOriginalFilename();
//设置日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String newName = sdf.format(new Date()) + fileName.substring(fileName.lastIndexOf('.'));
//把文件上传到服务器upload文件夹中,注意要在WebContent下建立文件夹upload不然会报错
FileOutputStream fos = new FileOutputStream(
req.getSession().getServletContext().getRealPath("/") + "upload/" + newName);
fos.write(file.getBytes());
fos.flush();
fos.close();
bookinfo.setBookimg("upload/" + newName);
// 调用添加方法,传bookinfo过去保存
System.out.println(bookinfo.toString());
return "test";
}
test 页面
<img src="${pageContext.request.contextPath}/${bookinfo.bookimg}">
这样就能显示图片了
需要注意的是: 中途可能报这个错
java.lang.ClassCastException: org.apache.catalina.connector.RequestFacade
cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest
可能原因如下
一: jsp页面的表单没有设置 enctype="multipart/form-data" 且要设置为"post"方式提交
<form action="" method="post" enctype="multipart/form-data">
二:springMvc中没有配置文件上传
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- set the max upload size100MB -->
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>
三: 必要的jar包没有导入
四:如果你上边的都没有问题,那么就是你只用了一个浏览器在测试,要清除缓存!!对,没有错,缓存!!
错误转载地址:https://blog.csdn.net/ling_du/article/details/52183735