天天看點

SpringMVC入門 檔案上傳和下載下傳

1.建立一個web項目,并且導入所需要的jar包

SpringMVC入門 檔案上傳和下載下傳

2.在web.xml檔案中,配置SpringMVC的前端控制器等等資訊

web.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <servlet>
 	<servlet-name>springmvc</servlet-name>
 	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 	<init-param>
 		<param-name>contextConfigLocation</param-name>
 		<!-- 加載springmvc-config.xml -->
 		<param-value>classpath:springmvc-config.xml</param-value>
 	</init-param>
 	<load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 	<servlet-name>springmvc</servlet-name>
 	<url-pattern>/</url-pattern>
 </servlet-mapping>
 	<!-- 處理post請求的中文亂碼-->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
			<init-param>
				<param-name>encoding</param-name>
				<param-value>utf-8</param-value>
			</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>
           

3.在src目錄下,建立并編寫SpringMVC的核心配置檔案springmvc-config.xml

springmvc-config.xml:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!-- 配置包掃描 -->
		<context:component-scan base-package="com.zzp.controller"/>
		<!-- 配置注解驅動 -->
		<mvc:annotation-driven/>
		<!-- 配置視圖解析器 -->
		<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<!-- 設定字首 -->
			<property name="prefix" value="/WEB-INF/jsp/"/>
			<!-- 設定字尾 -->
			<property name="suffix" value=".jsp"/>
		</bean>
		<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 設定請求編碼格式,必須與jsp中的pageEncoding屬性一緻,預設為ISO-8859-1 -->
		<property name="defaultEncoding" value="utf-8"/>
		<!-- 設定允許上傳檔案的最大值(2MB),機關為位元組 -->
		<property name="maxUploadSize" value="2097152"></property>
		</bean>
</beans>
           

4.在WebRoot目錄下,建立一個用于上傳檔案的頁面fileUpload.jsp

fileUpload.jsp:

<%@page import="java.net.URLEncoder"%>
<%@ 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%>" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" > 
    <title>上傳檔案測試</title>
  </head>
  
  <body>
   <form action="${pageContext.request.contextPath }/file/tolist" method="post" enctype="multipart/form-data">
   	<input type="file" name="uploadfile" multiple="multiple">
  	<input type="submit" value="上傳檔案">
   </form>
   <a href="${pageContext.request.contextPath }/file/download?filename=<%=URLEncoder.encode(" target="_blank" rel="external nofollow" zzp2e42d343-b2f2-4f24-9bbd-ea5a34add67a_.jpeg", "utf-8") %>">下載下傳桌面</a>
  </body>
</html>

           

5.在WEB-INF目錄下,建立jsp檔案夾,在檔案夾下建立show.jsp頁面用來提示檔案上傳成功與失敗

show.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%>" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" >
    <title>測試檔案上傳</title>
  </head>
  <body>
    ${msg }
  </body>
</html>

           

6.在src目錄下,建立一個com.zzp.controller包,在該包下建立一個用于檔案上傳的控制器FileController

FileController:

package com.zzp.controller;


import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/file")
public class FileController {
	@RequestMapping("/tofile")
	public String toflie(){
		return "fileUpload";
	}
	@RequestMapping("/tolist")
	public String FileList(List<MultipartFile> uploadfile,HttpServletRequest request,Model m){
		//設定上傳檔案的儲存位址目錄
		String path=request.getServletContext().getRealPath("/upload/");
		//判斷所上傳的檔案
		if(!uploadfile.isEmpty()&&uploadfile.size()>0){
			//循環輸出上傳的檔案
			for(MultipartFile item:uploadfile){
				//擷取上傳檔案的原始名稱
				String oldFile=item.getOriginalFilename();
				//擷取原始名稱的的字尾
				String newFile=oldFile.substring(oldFile.lastIndexOf("."));
				File filepath=new File(path);
				//如果儲存檔案的位址不存在,就先建立目錄
				if(!filepath.exists()){
					filepath.mkdirs();
				}
				//使用UUID重新命名上傳檔案名稱
				String EndFile="李三"+UUID.randomUUID()+"_"+newFile;
				try {
					//MultipartFile接口的方法完成檔案上傳到指定位置
					item.transferTo(new File(filepath, EndFile));
					//存入成功資訊,提示頁面成功
					m.addAttribute("msg", "上傳成功");
				} catch (Exception e) {
					e.printStackTrace();
					m.addAttribute("msg", "異常資訊:"+e.getMessage());	
				} 
			}
		}
		//跳轉到頁面
		return "show";
	}
	@RequestMapping("/download")
	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename) throws IOException{
		//filename檔案名編碼轉換成UTF-8,如果是UTF-8格式檔案名将會亂碼,或者不轉換檔案名編碼
		filename=new String(filename.getBytes("ISO-8859-1"),"UTF-8"); 
		//指定要下載下傳的檔案所在路徑
		String path=request.getServletContext().getRealPath("/upload/");
		//建立該檔案對象
		File file=new File(path+File.separator+filename);
		//對檔案名編碼,防止中文檔案亂碼
		filename=getFilename(request, filename);
		//設定響應頭
		HttpHeaders headers=new HttpHeaders();
		//通知浏覽器以下載下傳的方式打開檔案
		headers.setContentDispositionFormData("attachment", filename);
		//定義以流的形式下載下傳傳回檔案資料
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		//使用Spring MVC架構的ResponseEntity對象封裝傳回下載下傳資料
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
	}
	public String getFilename(HttpServletRequest request,String filename) throws UnsupportedEncodingException{
		//IE不同版本User-Agent中出現的關鍵詞
		String[] IEB={"MSIE","Trident","Edge"};
		//擷取請求頭代理資訊
		String userAgent=request.getHeader("User-Agent");
		for(String keyWord:IEB){
			if(userAgent.contains(keyWord)){
				//IE核心浏覽器,統一為utf-8編碼顯示
				return URLEncoder.encode(filename, "utf-8");
			}
		}
		//火狐等其他浏覽器統一為ISO-8859-1編碼顯示
		return new String(filename.getBytes("utf-8"),"ISO-8859-1");
	}
}

           

7.啟動項目,在浏覽器中輸入位址http://localhost:8080/SpringMVCFile/file/tofile,頁面顯示為:

SpringMVC入門 檔案上傳和下載下傳

繼續閱讀