十二、SpringMVC文件上传
SpringMVC提供了便捷的文件上传方式
引入依赖资源
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.5</version>
</dependency>
配置SpringMVC文件上传
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="104865760"/>
<property name="maxInMemorySize" value="102400"/>
</bean>
普通表单文件上传
<%--
Created by IntelliJ IDEA.
User: aries
Date: 2023/7/1
Time: 18:05
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="../js/jquery-3.7.0.js"></script>
</head>
<body>
<form action="/fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" value="上传" id="btn">
</form>
<img src="../upload/1.jpg" alt="">
</body>
</html>
@RequestMapping(value = "/fileUpload",method = RequestMethod.POST)
public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
//通过CommonsMultipartFile的方法直接写文件
file.transferTo(new File(realPath + "\\" + file.getOriginalFilename()));
return "";
}
AJAX文件上传
<%--
Created by IntelliJ IDEA.
User: aries
Date: 2023/7/1
Time: 18:05
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="../js/jquery-3.7.0.js"></script>
<script>
$(function () {
$("#btn").click(function () {
let forms=new FormData(document.getElementById("forms"));
$.ajax({
type:"POST",
url:"/fileUpload1",
processData:false,
contentType:false,
data:forms,
success:function (data) {
console.log(data);
$("#imgs").attr("src",data);
}
});
});
});
</script>
</head>
<body>
<form id="forms">
<input type="file" name="file" id="file">
<input type="button" value="上传" id="btn">
</form>
<img src="" alt="" id="imgs">
</body>
</html>
@ResponseBody
@RequestMapping(value = "/fileUpload1",method = RequestMethod.POST)
public String upload1(MultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
String show=realPath + "\\" + file.getOriginalFilename();
//通过CommonsMultipartFile的方法直接写文件
file.transferTo(new File(show));
return "\\upload"+show.substring(show.lastIndexOf("\\"));
}