1.在pom.xml文件中添加相關(guān)依賴
<!-- file upload-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
- 在springMVC配置文件中注冊文件解析器,同時配置springMVC的靜態(tài)資源視圖解析器,防止前端資源被springMVC的前端控制器攔截
注意:文件解析器的id必須為multipartResolver否則會報錯
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
<!-- 配置靜態(tài)資源視圖解析器-->
<mvc:resources mapping="/js/**" location="/js/"/>
<!-- 配置文件解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
3.編寫前端jsp頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上傳</title>
</head>
<body>
<h3> 文件上傳頁面</h3>
<form method="post" action="upload/testUpload" enctype="multipart/form-data">
<input type="file" name="upload"> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
5.編寫后臺Java代碼,注意:若使用@RequestParam("upload")注解,則參數(shù)需和<input type="file" name="upload">的name屬性值一致,若不使用則MultipartFile參數(shù)名必須和前端 <input type="file" name="upload">的name屬性值一致
package com.chen.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* @Description:
* @author: chenDing
* @date: 2020/3/6 9:02
*/
@Controller
@RequestMapping("/upload")
public class UploadController {
@RequestMapping("/testUpload") //注意MultipartFile參數(shù)名必須和前端 <input type="file" name="upload">的name屬性值一致
public String testUpload(HttpServletRequest request, @RequestParam("upload") MultipartFile upload) {
String realPath = request.getSession().getServletContext().getRealPath("/upload");
// String realPath1 = request.getServletContext().getRealPath("/upload");
// System.out.println(realPath);
// System.out.println(realPath1);
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
String filename = upload.getOriginalFilename();
// System.out.println(upload.getName()); /*表單字段name的值 upload*/
if ("".equals(filename)) {
return "error.jsp";
}
String replace = UUID.randomUUID().toString().replace("-", "");
filename = replace + "_" + filename;
try {
upload.transferTo(new File(realPath,filename));
} catch (IOException e) {
e.printStackTrace();
}
return "success.jsp";
}
}
測試截圖
image.png
image.png
image.png