多图片上传
- 前端【Vue】
(1)ElementUI
<el-form-item label="品牌logo" prop="brandLogo" :label-width="formLabelWidth">
<el-upload
action=""
list-type="picture-card"
:http-request="requestUpload"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-change="handleChange"
:before-upload="beforeUpload"
:file-list="fileList"
:limit="1"
:on-exceed="exceedTips"
:multiple="true"
>
<i class="el-icon-plus"></i>
<div slot="tip" class="el-upload__tip">图片上传数量:1张</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
</el-form-item>
(2)添加按钮(函数)
<!-- 弹窗按钮 -->
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="addBrand(addform)">确 定</el-button>
</div>
【< script >中】
(3)data中【不确定】
fileList:[],
addform:{
brandName:'',
dialogImageUrl:'',
dialogVisible:false,
brandStory:''
},
(4)methods中
// 添加品牌
async addBrand(addform){
this.dialogFormVisible = false;
var formData = new FormData;
formData.append("brandName",this.addform.brandName);
formData.append("brandStory",this.addform.brandStory);
this.fileList.forEach(function (file) {
//fileList里的file对象就是on-change钩子中的对象。后台是接收不到的
//能接收的是file.raw对象
formData.append("file",file.raw);
})
const {data:res}=await this.$http.post("/product/brand/addBrand",formData);
if(res.code==0){
this.$message.success("添加成功");
this.initFindSysUserList();
}
},
// 图片上传
requestUpload(data){
},
handleChange(file,fileList){
console.log("handleChange执行");
console.log(file)
this.fileList = fileList;
},
// 上传预处理,不含fileList参数
beforeUpload(file) {
console.log("beforeUpload执行");
console.log(file)
//判断文件是否上传重复
let existFile = this.fileList.slice(0, this.fileList.length - 1).find(f => f.name === file.name);
//上传文件是不是图片
let fileImg = file.type.indexOf("image/") === -1;
if (existFile || fileImg) {
this.msgError("文件格式错误或文件重复,请上传图片类型,如:JPG,PNG后缀的文件。");
//不匹配就pop
this.fileList.pop();
}
}
- 后端【SpringBoot】
public RespResult addBrand(BrandAddDTO brandAddDTO, MultipartFile[] file) throws IOException {
if (file != null) {
System.out.println("上传成功!");
// 判断后端是否收到了前端传来的图片
for (int i=0;i<file.length;i++) {
// 自动根据日期生成存放图片的文件夹
String format = new SimpleDateFormat("yyyy-MM-dd/").format(new Date());
// 上传文件的路径
String realPath = new String("D:/" + UPLOAD_PATH_PREFIX + format);
// 判断是否存在存放图片的指定文件夹,不存在则创建该目录
File tempFile = new File(realPath);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
System.out.println("上传文件路径" + realPath);
// 获得文件名
String fileName = file[i].getOriginalFilename();
System.out.println("文件名称=" + fileName);
File copyFile = new File(realPath + fileName);
// 实现上传
FileCopyUtils.copy(file[i].getBytes(), copyFile);
// 生成存入mysql的图片文件url地址信息
String fileUrl = realPath + fileName;
brandAddDTO.setBrandLogo(fileUrl);
// 填入数据库
return productService.addBrand(brandAddDTO);
}
}
return RespResult.error("上传文件不能为空!");
}