1.依赖包
commons-io-2.4.jar
commons-fileupload-1.2.2.jar
2.文件上传,依赖于MultipartFile
xml配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSizePerFile" value="500000000"></property>
<property name="defaultEncoding" value="utf-8"></property>
<property name="resolveLazily" value="true"></property>
</bean>
代码示例:
@RequestMapping("/testUpload")
public String testJson(@RequestParam("file") MultipartFile file,
@RequestParam("msg") String msg,HttpServletRequest request) throws IllegalStateException, IOException{
if(!file.isEmpty()){
//上传路径
/*String path=request.getServletContext().getRealPath("/images/");*/
String path="D:";
//上传文件名
String fileName=file.getOriginalFilename();
File filepath=new File(path,fileName);
//判断路径是否存在,如果不存在就创建一个
if(!filepath.getParentFile().exists()){
filepath.getParentFile().mkdirs();
}
//将上传文件保存到目标文档
file.transferTo(filepath);
}
return "hello";
}
如果表单中有多个文件上传,可以使用MultipartFile[]
3.文件下载
@RequestMapping("/testDownLoad")
public ResponseEntity<byte []> download(HttpServletRequest request) throws IOException{
//下载文件路径
/*String path=request.getServletContext().getRealPath("/images/");*/
String path="D:";
String filename="DSC_1240.JPG";
File file=new File(path,filename);
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
//通知浏览器以attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment", downloadFielName);
//application/octet-stream : 二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}