如何实现页面文件上传功能?
首先,修改页面的提交方式,改为多媒体提交
<form action="#" method="post"
enctype="multipart/form-data">
文件名称:<input name="fileImage" type="file"/> <br>
<input type="submit" value="提交"/>
</form>
然后需要在springmvc的配置文件中配置文件上传视图解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<propertyname="maxUploadSize" value="1048576"/>
<propertyname="defaultEncoding" value="UTF-8"/>
</bean>
设置CommonsMultipartResolver中的maxUploadSize来限制上传文件的大小,设置defaultEncoding来指定默认上传编码
接着需要处理页面提交的请求
@Controller
public class XXXX{
@RequestMapping("/file")
public String file(MultipartFile fileImage) throws IllegalStateException, IOException{
//方法中的参数 fileImage要和页面中的name属性值对应!!!
String fileName = fileImage.getOriginalFilename();// //1.获取文件名称
String filePath = "E:/jt-upload";// 2.定义要上传到哪个地方
File imageFile = new File(filePath);//3.判断该文件夹是否存在,不存在则创建
if(!imageFile.exists()){
imageFile.mkdirs();
}
fileImage.transferTo(new File(imageFile+"/"+fileName));//4.实现文件上传
System.out.println("文件上传成功!!!!");
return "redirect:/file.jsp";
}
}
文件上传的思路,嗯嗯,就是这样