标签:二进制 prope title head framework multipart down entity show
1.需要在springmvc配置文件中添加:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="数字"></property> </bean>
2.MultipartFile 工具类
@RequestMapping(value="fileupload",method=RequestMethod.POST) public String fileupload(String title,@RequestParam("upfiles") MultipartFile[] upfiles) { // 文件上传的代码 System.out.println(title); //空文件不去上传操作 for(MultipartFile upfile:upfiles) { if(upfile.getSize()>0) {
//文件上传服务器保存路径 String path="D:\\upload\\"; //上传文件的文件名 String filename = upfile.getOriginalFilename(); System.out.println(filename); File file = new File(path+filename); try { //上传文件开始 upfile.transferTo( file); } catch (Exception e) { e.printStackTrace(); } } } return "show"; }
如果是批量下载需要在MultipartFile属性前添加注释@RequestParam("前台提交文件name值")
@RequestMapping("download") public ResponseEntity<byte[]> download(String file){//创建下载路径 String filename = file; String path = "D:\\upload\\"; File file = new File(path + filename); HttpHeaders httpHeaders = new HttpHeaders(); //获取文件后缀 int i1 = filename.lastIndexOf("."); String substring = filename.substring(i1); //设置下载时文件名 filename=filename+substring;
//将文件名进行url转码 try { filename = URLEncoder.encode(filename,"utf-8"); } catch (UnsupportedEncodingException e) { System.out.println("上传异常"); e.printStackTrace(); } httpHeaders.setContentDispositionFormData("attachment", filename); //设置二进制流方式下载 httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); try { return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK); } catch (Exception e) { session.setAttribute("load","fail"); e.printStackTrace(); } return null; }
标签:二进制 prope title head framework multipart down entity show
原文地址:https://www.cnblogs.com/hwxxbc/p/10601661.html