一、导入依赖
在pom.xml添加这几个依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.22.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
二、在springMVC的配置文件添加配置
添加文件上传配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="10485760"/>
</bean>
三、开始配置控制器
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public Result upload(MultipartFile file,HttpSession session) throws IOException{
//获取服务器路径
String path = session.getServletContext().getRealPath("/upload");
//获取原文件名字
String originalName = file.getOriginalFilename();
//随机生成文件的名字
String newName = UUID.randomUUID().toString().replace("-", "")
+ originalName.substring(originalName.indexOf("."));
File file1 = new File(path);
//如果目录不存在 就创建目录
if(!file1.exists() || !file1.isFile()){
file1.mkdirs();
}
file1 = new File(file1, newName);
//生成新名字的目标文件是否存在 不存在则创建文件
if(!file1.exists()){
file1.createNewFile();
}
//io流input读取 output写入
try(
InputStream read = myFile.getInputStream();
OutputStream out = new FileOutputStream(file1);
){
byte[] bytes = new byte[1024];
int ch = 0;
while((ch = read.read(bytes)) != -1){
out.write(bytes, 0, ch);
}
out.flush();
out.close();
return Result.success("上传成功!", "http://localhost:8080/SpringMvcLogin01/uploadupload/"+newName);
}catch (Exception e){
e.printStackTrace();
return Result.error("上传失败!");
}
}
四、jsp页面
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2022/6/9
Time: 18:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<!--导入elementui 和 Vue相关的资源-->
<link rel="stylesheet" type="text/css" href="js/index.css">
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
</head>
<body>
<div id="app">
<el-upload
class="avatar-uploader"
action="http://localhost:8080/SpringMvcLogin01/upload/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
<script>
//文件上传组件name默认属性值是file
const app = new Vue({
el:"#app",
data:{
imageUrl: ''
},
methods: {
handleAvatarSuccess(res, file) {
//照片回显服务器照片资源地址
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 2048 / 2048 < 2;
if (!isJPG && !isPNG) {
this.$message.error('上传头像图片只能是 PNG,JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return (isPNG || isJPG) && isLt2M;
}
}
})
</script>
</body>
</html>