文件上传
1. spring配置文件加入
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<!--不写的话默认10k,小于10k不会保存-->
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
2. jsp页面
<form action="<%=request.getContextPath()%>/upDown/fileUpLoad" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交单文件"/>
</form>
<form action="<%=request.getContextPath()%>/upDown/filesUpLoad" method="post" enctype="multipart/form-data">
<p> 选择文件:<input type="file" name="files">
<p> 选择文件:<input type="file" name="files">
<p> 选择文件:<input type="file" name="files">
<input type="submit" value="提交多文件">
</form>
3. controller层
1)单文件上传
@RequestMapping(value="/fileUpLoad")
@ResponseBody
public void upload(HttpServletRequest request,@RequestParam("file") CommonsMultipartFile file) throws Exception{
//获取保存路径
ServletContext servletContext = request.getServletContext();//获取ServletContext的对象 代表当前WEB应用
String realPath = servletContext.getRealPath("/uploads/");//得到文件上传目的位置的真实路径
File file1 = new File(realPath);
//如果该目录不存在,新建
if(!file1.exists()){
file1.mkdir();
}
//文件名
String prefix = UUID.randomUUID().toString();
prefix = prefix.replace("-","");
String fileName = prefix+"_"+file.getOriginalFilename();
//保存文件,这是spring封装好方法,具体流程是先读到输入流,再写到输出流
file.transferTo(new File(realPath+fileName));
}
2 ) 多文件上传
@RequestMapping(value="/filesUpLoad")
@ResponseBody
//jsp的input标签name要改为files;@RequestParam("files")可以不加,CommonsMultipartFile和MultipartFile的区别
public void uploads(HttpServletRequest request,MultipartFile[] files) throws Exception{
//MultipartFile可以不加@RequestParam,即MultipartFile file
//获取保存路径
ServletContext servletContext = request.getServletContext();//获取ServletContext的对象 代表当前WEB应用
String realPath = servletContext.getRealPath("/uploads/");//得到文件上传目的位置的真实路径
File file1 = new File(realPath);
//如果该目录不存在,新建
if(!file1.exists()){
file1.mkdir();
}
//文件名
String prefix = UUID.randomUUID().toString();
prefix = prefix.replace("-","");
String fileName;
for(MultipartFile file:files){
fileName = prefix+"_"+file.getOriginalFilename();
file.transferTo(new File(realPath+fileName));
}
}
CommonsMultipartFile和MultipartFile好像只有一个区别,就是MultipartFile前面可以不加@RequestParam。
也可以直接从request中获取
@RequestMapping("/import")
@ResponseBody
public void uploads(HttpServletRequest request,HttpServletResponse response){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> multipartFile=multipartRequest.getFiles("file");
try {
//单文件实际就是获取list的第一个值
multipartFile.get(0).transferTo(new File(""));
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}