Springmvc文件上傳和下載


使用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"?>
<beans
	xmlns="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.xsd
						http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
						http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
						http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
						http://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;

@Controller
public 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;
	   }
	
	
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章