使用SpringMVC实现文件上传和下载
文件上传
第一步,加入jar包:
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
第二步,在SpringMVC配置文件中配置CommonsMultipartResovler
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> //最大上传文件大小 <property name="maxUploadSize" value="1048576"></property> </bean>
第三步,前端表单 注意 【POST请求,file类型,enctype="multipart/form-data"】
<form action="${pageContext.request.contextPath }/testUpload" method="post" enctype="multipart/form-data"> File:<input type="file" name="file"><br> desc:<input type="text" name="desc"><br> <input type="submit" value="submit"><br> </form><br>
第四步,在controller层创建方法
1 @RequestMapping(value="/testUpload",method=RequestMethod.POST) 2 private String testUpload(HttpServletRequest request,@RequestParam(value="desc")String desc,@RequestParam(value="file") CommonsMultipartFile file) { 3 4 InputStream inputStream = null; 5 OutputStream outputStream = null; 6 ServletContext servletContext = request.getServletContext(); 7 //获取文件存放的真实路径 8 String realPath = servletContext.getRealPath("/upload"); 9 //为了避免多次上传同一个文件导致命名重复,在文件名前加UUID前缀 10 String prefix=UUID.randomUUID().toString(); 11 prefix=prefix.replace("-", ""); 12 String fileName=prefix+"_"+file.getOriginalFilename(); 13 14 File file2=new File(realPath); 15 //检查文件目录是否存在,若不存在就创建目录 16 if(!file2.exists()){ 17 file2.mkdirs(); 18 } 19 20 try { 21 inputStream=file.getInputStream(); 22 outputStream=new FileOutputStream(new File(realPath+"/"+fileName)); 23 //设置缓冲区 24 byte[]buffer=new byte[1024]; 25 int len=0; 26 //循环检测文件是否上传完成,未完成就向写入输出流 27 while((len=inputStream.read(buffer)) != -1){ 28 outputStream.write(buffer, 0, len); 29 outputStream.flush(); 30 } 31 } catch (IOException e) { 32 // TODO Auto-generated catch block 33 e.printStackTrace(); 34 } finally{ 35 //关闭输入输出流 36 if(outputStream !=null){ 37 try { 38 outputStream.close(); 39 inputStream.close(); 40 } catch (IOException e) { 41 // TODO Auto-generated catch block 42 e.printStackTrace(); 43 } 44 } 45 } 46 47 return "success"; 48 }
文件下载
用ResponseEntity<byte[]> 返回值完成文件下载;在jsp页面给出链接即可。
jsp页面链接地址:
<a href="${pageContext.request.contextPath }/testResponseEntity">下载链接</a><br>
在controller层创建方法
1 @RequestMapping(value="/testResponseEntity") 2 ResponseEntity<byte[]>testResponseEntity(HttpServletRequest request)throws Exception{ 3 ServletContext servletContext = request.getServletContext(); 4 //获取要下载的文件的文件名 5 String fileName="喜剧之王.mp3"; 6 //获取要下载的文件的真实路径 7 String realPath = servletContext.getRealPath("/WEB-INF/"+fileName); 8 //创建输入流 9 InputStream inputStream=new FileInputStream(new File(realPath)); 10 11 byte[]body=new byte[inputStream.available()]; 12 inputStream.read(body); 13 MultiValueMap<String, String>headers=new HttpHeaders(); 14 15 //设置头信息和字符集 16 fileName = new String(fileName.getBytes("gbk"),"iso8859-1"); 17 headers.set("Content-Disposition", "attachment;filename="+fileName); 18 19 HttpStatus statusCode = HttpStatus.OK; 20 ResponseEntity<byte[]>responseEntity =new ResponseEntity<byte[]>(body, headers, statusCode); 21 22 return responseEntity; 23 }