SSM 准备工作
一、准备文件上传的jar包
<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.3.3</version>
</dependency>
二、配置Spring MVC 配置文件
放在beans中
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
三、编写 Controller 接收文件
@RequestMapping("/uploadImage")
public String megerUserShopImg(MultipartFile file) {
//判断所上传文件是否存在
if (file.isEmpty()) {
return "上传错误";
}
//获取上传文件的原始名称
String originalFilename = file.getOriginalFilename();
//设置上传文件的保存地址目录
String dirPath = "D:/user/";
File filePath = new File(dirPath);
//如果保存的地址不存在,就先创建目录
if (!filePath.exists()) {
filePath.mkdirs();
}
//获取当前文件的后缀
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
//使用UUID重新命名上传的文件名称(UUID(唯一识别码)+原始文件名称后缀)
String newFileName = UUID.randomUUID() + "." + suffix;
try {
//创建可能会有错误,强制添加异常
file.transferTo(new File(dirPath + newFileName));
} catch (IOException e) {
e.printStackTrace();
return "上传错误";
}
System.out.println(dirPath + newFileName);
return newFileName;
}
Vue + Element UI 图片上传组件
upload中最重要的三个参数
参数 | 作用 |
---|---|
name | 后台接收的参数(没有会报错) |
action | 后台请求路径地址(http://localhost:8080/user/uploadImage) |
on-success | 访问成功调用的参数 |
<!-- 主要文件上传部分 -->
<el-upload
class="upload-demo"
name="file"
action="/api/user/uploadImage"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
:limit="9"
:on-success="handleSuccess"
:on-exceed="handleExceed"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">
只能上传jpg/png文件,且不超过5MB
</div>
</el-upload>
<!-- 主要返回事件部分 -->
//成功返回方法
handleSuccess(res, file) {
this.$message({
type: "info",
message: "图片上传成功",
duration: 6000,
});
console.log(res);
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(
`请勿频繁上传图片操作,您已经选择 ${files.length} 个文件,真的需要重新上传,请刷新页面`
);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
},
最后
在进行一些业务处理即可