文件上傳
要是使用Servlet對文件上傳進行處理,我們還是能明顯的感覺到代碼量太多了,自己處理起來還是有一些麻煩,Spring作爲一個優秀的框架,它也爲我們考慮到了文件上傳,下面演示使用SpringMvc上傳文件的例子。
環境準備
- 創建Maven的web項目。
- 導入相關依賴
<!--Spring的大部分依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!--commons-io文件上傳依賴-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
- 配置SpringMvc的配置文件(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: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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自動掃描包,讓指定包下的註解生效,由Spring容器統一管理-->
<context:component-scan base-package="com.ara.controller"/>
<!--讓Spring不處理靜態資源-->
<mvc:default-servlet-handler />
<!--
支持mvc註解驅動
在Spring中一般採用@RequestMapping註解來完成映射關係
要使@RequestMapping註解生效
必須向上下文中註冊DefaultAnnotationHandlerMapping
和一個AnnotationMethodHandlerAdapter實例
這兩個實例分別在類級別和方法級別中處理
而annotation-driven配置幫助我們自動完成上述兩個實例的注入
-->
<mvc:annotation-driven />
<!--視圖解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<!--視圖前綴-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--視圖後綴-->
<property name="suffix" value=".jsp"/>
</bean>
<!--文件上傳配置-->
<!--這裏需要注意bean的id必須爲multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--請求的編碼格式,必須和頁面的編碼格式一致,默認爲ISO-8859-1-->
<property name="defaultEncoding" value="UTF-8"/>
<!--上傳文件大小限制 單位爲字節(10M=10485760)-->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
</beans>
這裏特別注意文件上傳的配置。
- 配置web.xml文件
<servlet>
<servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 編寫測試Controller
package com.ara.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@RequestMapping("/hello")
@ResponseBody
public String hello(){
System.out.println("hello");
return "hello";
}
}
- 測試環境是否OK
環境OK。
先保證環境沒問題,再進行下面的操作。
1.編寫測試頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上傳文件</title>
</head>
<body>
<h2>方式1</h2>
<form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上傳" />
</form>
<br>
<hr>
<h2>方式2</h2>
<form action="${pageContext.request.contextPath}/file/upload2" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上傳" />
</form>
<br>
<hr>
<h2>混合表單</h2>
<form action="${pageContext.request.contextPath}/file/upload3" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br>
<input type="text" name="name" /><br>
<input type="submit" value="提交" />
</form>
</body>
</html>
2.編寫處理文件上傳的Controller
package com.ara.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@RestController
@RequestMapping("/file")
public class FileController {
/**
* 文件上傳1
*
* @param file 提交表單的文件name值
* @param request 請求對象
* @return 返回上傳結果
* @throws IOException
*/
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//獲取文件名
String uploadFileName = file.getOriginalFilename();
//如果文件名爲空
if (uploadFileName == null || uploadFileName.equals("")) {
return "fail!";
}
System.out.println("上傳的文件名爲:" + uploadFileName);
//獲取文件上傳的存放路徑
String path = request.getRealPath("/load");
//如果文件不存在就創建
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
System.out.println("文件保存地址:" + realPath);
//獲取文件輸入流
InputStream is = file.getInputStream();
//文件輸出流
FileOutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
//讀寫文件
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
os.flush();
}
//關閉資源
os.close();
is.close();
return "OK";
}
/**
* 文件上傳2
*
* @param file 表單中文件輸入框的name值
* @param request 請求對象
* @return 放回上傳結果
* @throws IOException
*/
@RequestMapping("/upload2")
public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//獲取文件名
String uploadFileName = file.getOriginalFilename();
//如果文件名爲空
if (uploadFileName == null || uploadFileName.equals("")) {
return "fail!";
}
System.out.println("上傳的文件名爲:" + uploadFileName);
//獲取文件上傳的存放路徑
String path = request.getRealPath("/load");
//如果文件不存在就創建
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
System.out.println("文件保存地址:" + realPath);
//文件直接保存在指定地方
file.transferTo(new File(realPath + "/" + uploadFileName));
return "OK";
}
/**
* 表單中含有其他提交項的上傳
*
* @param file 提交表單的文件name值
* @param name 表單中提交的name值
* @param request 請求對象
* @return 返回提交結果
* @throws IOException
*/
@RequestMapping("/upload3")
public String upload3(@RequestParam("file") CommonsMultipartFile file, String name, HttpServletRequest request) throws IOException {
//獲取文件名
String uploadFileName = file.getOriginalFilename();
//如果文件名爲空
if (uploadFileName == null || uploadFileName.equals("")) {
return "fail!";
}
System.out.println("上傳的文件名爲:" + uploadFileName);
System.out.println("name: " + name);
//獲取文件上傳的存放路徑
String path = request.getRealPath("/load");
//如果文件不存在就創建
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
System.out.println("文件保存地址:" + realPath);
file.transferTo(new File(realPath + "/" + uploadFileName));
return "OK";
}
}
3.測試
- 方式1
- 方式2
- 方式3
上述上傳都成功了。