Springmvc文件上传和下载

来源:互联网 发布:做淘宝网店要实体店吗 编辑:程序博客网 时间:2024/05/04 06:32


使用springMVC包装的解析器(CommonsMultipartResolver)进行文件上传控制 需要引入 apache的 common-fileupload组件包



 1:使用表单post提交

  

input.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'input.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>   <form action="${pageContext.request.contextPath}/uploads.action" enctype="multipart/form-data" method="post">   <input type="file" name="myFile"/>    <input type="submit" value="提交">      <a href="${pageContext.request.contextPath}/fileDowload.action?fileName=a.txt">下载</a>      </form>           </body></html>

2:springmvc配置文件中添加文件解析器:

 ps:名称必须使用  multipartResolver 因为spring容器使用名称注入 文件上传解析器



<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"><context:component-scan base-package="cn"></context:component-scan><!-- 文件解析器 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxInMemorySize" value="1048576"></property></bean></beans>

3.文件上传和下载

  


package cn.zj.mvc.lesson02;import java.io.File;import java.io.IOException;import java.net.URLEncoder;import javax.servlet.http.HttpServletResponse;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.util.FileCopyUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;@Controllerpublic class DownUpload {public String filePath="E:/class/springmvc/upload/";@RequestMapping(value="/uploads")public String fileUpload(@RequestParam("myFile") MultipartFile file,HttpServletResponse response) throws IllegalStateException, IOException{//file.getOriginalFilename() 是获取文件名File upFile=new File(filePath+file.getOriginalFilename());file.transferTo(upFile);response.getWriter().println("succeed");return null;} @RequestMapping(value="/fileDowload")  public ResponseEntity<byte[]> fileDowload(String fileName) throws Exception{         /**    * 需要注意的  跳转方式必须是form表单 ,且为post方式提交    */          //需要下载的目标文件       File file=new File(filePath+fileName);              //读取目标文件为二进制数组       byte[] fileByte=FileCopyUtils.copyToByteArray(file);                     //设置响应头       HttpHeaders hh=new HttpHeaders();       //设置下载的文件的名称  且转码       hh.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));             /*        * 构建ResponseEntity对象           *  1:传入文件字节数组          *  2: 文件名        *  3:状态码  HttpStatus.CREATED  =200        */       ResponseEntity<byte[]> re=new ResponseEntity<byte[]>(fileByte, hh, HttpStatus.CREATED);       return re;   }}