之前我們介紹了在無架構支援的環境下如何進行檔案上傳的方式,此種方式比較基礎,相對而言比較麻煩一點。
在接下來的文章中,我們将借助spring web mvc架構簡化檔案上傳的操作。
一、建立web項目,導入spring web mvc支援包以及上傳檔案jar包
二、在web.xml中配置spring mvc入口,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<!-- spring mvc入口 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
<!-- 配置編碼過濾器,解決中文亂碼 -->
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
三、編寫jsp頁面
upload.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>upload.jsp</title>
</head>
<body>
<h2>檔案上傳功能示範</h2>
<h2>${message}</h2>
<c:url var="action" value="/upload/upload-action.form"/>
<form action="${action}" method="post" enctype="multipart/form-data">
<p>圖檔:<input type="file" name="image"/></p>
<p>拍攝地點:<input type="text" name="location"/></p>
<h3><input type="submit" value="上傳圖檔"/></h3>
</form>
</body>
</html>
success.jsp:上傳成功提示頁面
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>success.jsp</title>
</head>
<body>
<h2>${pathName}</h2>
</body>
</html>
四、編寫背景上傳代碼:UploadController.java
package com.tarena.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import javax.naming.directory.DirContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import com.sun.org.apache.bcel.internal.generic.NEW;
@Controller
@RequestMapping("/upload")
public class UploadController implements Serializable {
/**
* 顯示上傳檔案頁面
* @return
*/
@RequestMapping("/upload.form")
public String uploadForm(){
return "upload";
}
/**
* 處理上傳檔案請求
* @throws IOException
*/
@RequestMapping("/upload-action.form")
public String uploadAction(MultipartFile image,String location,ModelMap map,HttpServletRequest request) throws IOException{
//擷取圖檔原始檔案名
String name=image.getOriginalFilename();
//input輸入框name屬性值:image
//String fieldName=image.getName();
//org.springframework.web.multipart.MultipartFile
//擷取輸入流,送出圖檔的資料内容(圖檔資料,大資料此種方式友善)
//InputStream inputStream=image.getInputStream();
//圖檔資料(小資料此種方式友善)
byte[] bytes=image.getBytes();
//圖檔的檔案長度
//long size=image.getSize();
//存放路徑
String path=request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
File dir=new File(path);
if(! dir.exists()){
dir.mkdir();
}
File file=new File(dir,name);
FileOutputStream out=new FileOutputStream(file);
out.write(bytes);
out.close();
//file.getCanonicalPath():傳回此抽象路徑名的規範路徑名字元串
request.setAttribute("pathName","上傳成功:"+file.getCanonicalPath()+"拍攝于:"+location);
return "success";
}
/**
* 檔案下載下傳
* 現伺服器項目目錄下有該圖檔:暴風截圖201491415793151.jpg
* 通路路徑為;localhost:8080/SpringUpload/upload/get-file.form?name=暴風截圖201491415793151.jpg 時,
* 将會下載下傳看到圖檔
*/
@RequestMapping("/get-file.form")
public void getImage(String name,HttpServletRequest request,HttpServletResponse response)throws IOException{
//将name對應的圖檔讀取回來,然後寫入到response流中
//name是下載下傳的檔案名
if(name.endsWith(".png")){
response.setContentType("image/png");
}
String path=request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
File file=new File(path,name);
FileInputStream input=new FileInputStream(file);
OutputStream output=response.getOutputStream();
IOUtils.copy(input, output);
input.close();
output.close();
}
/**
* 處理控制器類上的異常
* @param request
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler
public String execute(HttpServletRequest request,Exception e) throws Exception{
//處理IO異常
if(e instanceof IOException){
e.printStackTrace();
request.setAttribute("message", "上傳失敗!");
return "upload";
}
//處理檔案上傳超出限制大小時抛出的異常
if(e instanceof MaxUploadSizeExceededException){
e.printStackTrace();
request.setAttribute("message", "檔案過大!");
return "upload";
}
throw e;
}
}
五、在項目src目錄下建立spring-mvc.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 加上此配置,則可以省略HandlerMapping配置 -->
<mvc:annotation-driven/>
<!-- 開啟元件掃描 -->
<context:component-scan base-package="com.tarena"/>
<!-- 視圖解析器 -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 支援檔案上傳的Bean -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 限制檔案上傳的大小不超過100kb -->
<!-- <property name="maxUploadSize" value="102400"/> -->
<!-- <property name="resolveLazily" value="true"/> -->
</bean>
</beans>
到了這裡,包含檔案上傳和下載下傳的demo也就完成了,經本人測試通過,在此就示範了,大家自己測吧。
整個代碼下載下傳位址:http://yunpan.cn/cQTKT9wiHKB7Q 通路密碼 743c