SpringMVC实现文件上传和下载功能 SpringMVC实现文件上传和下载功能
AltErNatiVe 人气:0文件上传
第一步,加入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层创建方法
@RequestMapping(value="/testUpload",method=RequestMethod.POST) private String testUpload(HttpServletRequest request,@RequestParam(value="desc")String desc,@RequestParam(value="file") CommonsMultipartFile file) { InputStream inputStream = null; OutputStream outputStream = null; ServletContext servletContext = request.getServletContext(); //获取文件存放的真实路径 String realPath = servletContext.getRealPath("/upload"); //为了避免多次上传同一个文件导致命名重复,在文件名前加UUID前缀 String prefix=UUID.randomUUID().toString(); prefix=prefix.replace("-", ""); String fileName=prefix+"_"+file.getOriginalFilename(); File file2=new File(realPath); //检查文件目录是否存在,若不存在就创建目录 if(!file2.exists()){ file2.mkdirs(); } try { inputStream=file.getInputStream(); outputStream=new FileOutputStream(new File(realPath+"/"+fileName)); //设置缓冲区 byte[]buffer=new byte[1024]; int len=0; //循环检测文件是否上传完成,未完成就向写入输出流 while((len=inputStream.read(buffer)) != -1){ outputStream.write(buffer, 0, len); outputStream.flush(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ //关闭输入输出流 if(outputStream !=null){ try { outputStream.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return "success"; }
文件下载
用ResponseEntity<byte[]> 返回值完成文件下载;在jsp页面给出链接即可。
jsp页面链接地址:
复制代码 代码如下:
<a href="${pageContext.request.contextPath }/testResponseEntity" rel="external nofollow" >下载链接</a>
在controller层创建方法
@RequestMapping(value="/testResponseEntity") ResponseEntity<byte[]>testResponseEntity(HttpServletRequest request)throws Exception{ ServletContext servletContext = request.getServletContext(); //获取要下载的文件的文件名 String fileName="喜剧之王.mp3"; //获取要下载的文件的真实路径 String realPath = servletContext.getRealPath("/WEB-INF/"+fileName); //创建输入流 InputStream inputStream=new FileInputStream(new File(realPath)); byte[]body=new byte[inputStream.available()]; inputStream.read(body); MultiValueMap<String, String>headers=new HttpHeaders(); //设置头信息和字符集 fileName = new String(fileName.getBytes("gbk"),"iso8859-1"); headers.set("Content-Disposition", "attachment;filename="+fileName); HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]>responseEntity =new ResponseEntity<byte[]>(body, headers, statusCode); return responseEntity; }
加载全部内容