springMVC实现文件上传和下载

1.文件上传:

  • 依赖:
     <!-- 文件上传依赖 -->
    	<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    	<dependency>
    	    <groupId>commons-fileupload</groupId>
    	    <artifactId>commons-fileupload</artifactId>
    	    <version>1.3.1</version>
    	</dependency>
    	<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    	<dependency>
    	    <groupId>commons-io</groupId>
    	    <artifactId>commons-io</artifactId>
    	    <version>2.6</version>
    	</dependency>

     

  • springmvc.xml配置文件:

    <!--文件上传解析器  -->
        <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  
        id="multipartResolver">
        	<property name="maxUploadSize">
        		<value>52428800</value>
        	</property>
        </bean>

     

  • 实现方法:

    	@RequestMapping("/upload")
    	public String  fileUpload(HttpServletRequest request,
    			HttpServletResponse response,MultipartFile 
    			headImg,String username,HttpSession session) throws IOException, 
    	ServletException {				
    		System.out.println("fileUpload......username:"+username);
    		String fileName = headImg.getOriginalFilename();
    		session.setAttribute("fileName", fileName);
    		System.out.println("fileUpload......文件名称:"+fileName);
    		headImg.transferTo(new File("E:\\upload/"+fileName));
    		return "user";
    	}

     

  • jsp页面:

    <%-- isELIgnored 开启el表达式的支持 --%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"  isELIgnored="false"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <H1>springwebmvc-test</H1>
    <body>
    <form action="${pageContext.request.contextPath}/user/upload"  method="post" enctype='multipart/form-data'><br>
    	用户名:<input type="text" name="username"/><br>
    	头像:<input type="file" name="headImg"/><br>
    	<input type="submit" value="提交"/>
    </form>
    <H5><a href="${pageContext.request.contextPath}/user/download2?filename=${sessionScope.fileName}">文件下载:${sessionScope.fileName}</a></H5>
    request: ${requestScope.msg}<br>
     session:${sessionScope.fileName}<br>
     
       
    </body>
    </html>

    2.文件下载方法:

  • 
    	/** 文件下载的基本实现方式
    	 * @throws IOException 
    	 * @throws ServletException 
    	 * 
    	 * @Title: addUser   
    	 * @Description: TODO(描述这个方法的作用)   
    	 */
    	@RequestMapping("/downLoad1")
    	public void downLoad1(HttpServletRequest request,
    			HttpServletResponse response,
    			HttpSession session) throws IOException, ServletException {
    		
    		System.out.println("downLoad..."+session.getAttribute("fileName"));
    		File file =new File("E:\\upload/1.jpg");
    		//设置响应 头和客户端显示文件名
    		response.setCharacterEncoding("utf-8");
    		response.setContentType("multipart/form-data");
    		response.setHeader("Content-Disposition", "attachement;filename="+file.getName());
    		//打开源文件流
    		InputStream inputStream=new FileInputStream(file);
    		//激活下载流
    		ServletOutputStream outputStream=response.getOutputStream();
    		//复制文件流,将文件流写出
    		byte[] buffer=new byte[1024];
    		int num=0;
    		while((num=inputStream.read(buffer))!=-1) {
    			outputStream.write(buffer,0,num);
    		}
    		outputStream.close();
    		inputStream.close();
    	}
    	/** springmvc文件下载的实现方式
    	 * @throws IOException 
    	 * @throws ServletException 
    	 * 
    	 * @Title: addUser   
    	 * @Description: TODO(描述这个方法的作用)   
    	 */
    	 @RequestMapping(value="/download2",method=RequestMethod.GET) //匹配的是href中的download请求
    	    public ResponseEntity<byte[]> download2(HttpServletRequest request,@RequestParam("filename") String filename,
    	            Model model) throws IOException{
    	        
    	        String downloadFilePath="E:\\\\upload";//从我们的上传文件夹中去取
    	        
    	        File file = new File(downloadFilePath+File.separator+filename);//新建一个文件
    	        
    	        HttpHeaders headers = new HttpHeaders();//http头信息
    	        
    	        String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");//设置编码
    	        
    	        headers.setContentDispositionFormData("attachment", downloadFileName);
    	        
    	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	        
    	        //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
    	        
    	        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
    	        
    	    }

     

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值