可以使用图片与表单分别上传的思路
选中图片后,可以将图片先上传,随后返回图片地址,并添加到表单中,如皋用户取消上传图片,调用删除接口,将图片从服务器中删除。
大致代码如下:
<el-upload
class="upload-demo"
ref="upload"
action="fakeaction"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="true"
:http-request="setUrl"
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
函数:
handleChange(value) {
console.log(value);
},
// 图片
handleRemove(file, fileList) {
that.sysUserImgDelete(this.form).then(res => {
this.form.identificationPhoto="";
console.log("图片移除成功")
})
},
handlePreview(file) {
console.log(file);
},
setUrl(params){
const file = params.file;
// 根据后台需求数据格式
const form = new FormData();
// 文件对象
form.append("file", file);
that.sysUserImgUpload(form).then(res =>{
this.form.identificationPhoto = res;
}).catch((error) => {
console.log(error);
});
},
js代码:
// 引入axios封装文件
import request, { mockIP, backendIP } from "@/utils/request";
// import { replacePath } from '@/utils/index'
var IP = "";
// backendIP = mockIP;//切换全局模拟IP地址
// 用户管理 - 添加员工
// 用户管理 - 头像上传
export function sysUserImgUpload(data) {
IP = false ? mockIP : backendIP;
return request({
url: IP + "/business/staffinfo/imgup",
method: "post",
data: data,
});
}
// 用户管理 - 头像删除
export function sysUserImgDelete(data) {
IP = false ? mockIP : backendIP;
return request({
url: IP + "/business/staffinfo/imgdelete",
method: "post",
data: data,
});
}
后端代码(由于大家的存储地址都不一样,我是存放在OSS中,大家根据自己的做法再做更改吧,就不全放出来了,有需要可以留言获取):
/**
* 信息
*/
@ApiOperation("-图片上传")
@PostMapping("/imgup")
// @RequiresPermissions("business:staffinfo:info")
public Result<String> imgUp(@ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file) throws IOException {
Result<String> result = new Result<>();
InputStream inputStream = file.getInputStream();
String filename = file.getOriginalFilename();
String pictureUrl = fileService.upload(inputStream, "员工证件照", filename);
result.setResult(pictureUrl);
return result;
}
/**
* 信息
*/
@ApiOperation("-图片删除")
@PostMapping("/imgdelete")
// @RequiresPermissions("business:staffinfo:info")
public Result imgUrl(@RequestBody StaffInfoDO staffInfo){
fileService.removeFile(staffInfo.getIdentificationPhoto());
return Result.ok();
}
经由以上操作,可以实现图片上传而且用户取消上传哦,在服务器删除图片的操作,避免了用户多次上传图片对服务器的存储造成的压力,节省资源!