SpringMVC實現檔案上傳到Tomcat指定目錄(包含pojo提交)
阿新 • • 發佈:2019-02-01
這段時間一直在考慮畢業設計的事,在註冊上面可能會設計到檔案上傳,因此看了一下spring的官方文件中有相關的內容,整理了一下與大家分享,第一次寫博文
3、 web.xml中配置前端控制器及編碼方式
6、到此基本的demo已經完成(需要新增的jar在圖片中已經列出,有幾個jar是用不到的如 jms請自定取捨 )
我們來訪問 http://localhost:8080/FileUpload/
也會有一些不合理的地方,希望大家指正。
檔案上傳demo的目錄結構
1、在spring中我感覺最重要的就是配置檔案,所以優先把配置檔案說明一下(命名是按照spring的預設的命名方式,放在WEB-INF目錄下)
即圖中的 mvc-servlet.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:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd" default-autowire="byName" default-lazy-init="true"> <!-- 啟用註解 --> <mvc:annotation-driven/> <!-- 掃描的處理器(Controller)的包 --> <context:component-scan base-package="controller"/> <!-- 檔案上傳表單的檢視解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 這裡的value要配置的比上傳檔案的大小要大一些 -->
<property name="maxUploadSize" value="5151400"/>
</bean>
</beans>
2、 接下來是pojo(用於測試的,在FileUploadController中並沒有進行特殊的處理,比如存入資料庫,但是這個步驟使用mybatis就可以完成,在FileUploadController
中回將上傳的檔案重新命名並存入tomcat伺服器指定目錄fileDir下)
package model; public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
3、 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"> <display-name></display-name> <!-- 解決post亂碼 --> <filter> <filter-name>characterEncodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置前端控制器 --> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 預設顯示的頁面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
4、頁面部分
預設頁面 index.jsp(這裡需要注意form中的
enctype="multipart/form-data)
<%@ 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 'index.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">
</head>
<body>
<form method="post" action="<%=path%>/form.do" enctype="multipart/form-data">
姓名:<input type="text" name="name"/><br>
檔案: <input type="file" name="file"><br>
<input type="submit" value="上傳"/>
</form>
</body>
</html>
其他success及error是簡單的提示,就不在贅述貼上了
5、重要的Controller處理器FileUploadController
package controller;
import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController{
@RequestMapping(value="/form",method=RequestMethod.POST)
public String handleFormUpload(HttpServletRequest request,@ModelAttribute("user") User user, String name,@RequestParam("file") MultipartFile file) throws Exception{
if(!file.isEmpty()){
//可以對user做一些操作如存入資料庫
//以下的程式碼是將檔案file重新命名並存入Tomcat的webapps目錄下專案的下級目錄fileDir
String fileRealName = file.getOriginalFilename(); //獲得原始檔名;
int pointIndex = fileRealName.indexOf("."); //點號的位置
String fileSuffix = fileRealName.substring(pointIndex); //擷取檔案字尾
UUID FileId = UUID.randomUUID(); //生成檔案的字首包含連字元
String savedFileName = FileId.toString().replace("-","").concat(fileSuffix); //檔案存取名
String savedDir = request.getSession().getServletContext().getRealPath("fileDir"); //獲取伺服器指定檔案存取路徑
File savedFile = new File(savedDir,savedFileName );
boolean isCreateSuccess = savedFile.createNewFile();
if(isCreateSuccess){
file.transferTo(savedFile); //轉存檔案
}
return "redirect:success.jsp";
}
return "redirect:error.jsp";
}
}
6、到此基本的demo已經完成(需要新增的jar在圖片中已經列出,有幾個jar是用不到的如 jms請自定取捨 )
我們來訪問 http://localhost:8080/FileUpload/
填入姓名並選擇檔案,點選上傳
然後我們看一下檔案是否生成(檔名不是原來的名字是因為在FileUploadController中用生成的UUID進行了重新命名)
7、今天的分享就到這裡,希望能給大家帶來幫助,有什麼不合適的地方希望大家指正。