vue2 上传图片
一、前端
<el-row> <el-form-item label="上传文件" props="fileList"> <el-upload ref="upload" action="#" list-type="picture-card" multiple accept="image/jpeg, image/jpg, image/png,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf,application/msword" :file-list="fileList" :auto-upload="false" :on-change="handleChange" :on-remove="handleRemove" :on-preview="handlePreview" > <i slot="default" class="el-icon-plus" ></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog> </el-form-item> </el-row>
二、逻辑,判断文件大小以及重复图片校验
uploadImageSize(that, file, fileList) { if (file.size / 1024 / 1024 > 10) { publicJS.showMessage("单个文件大小不能超过10MB", publicJS.ErrorType); let index = that.fileList.indexOf(file) //删除超过10M的照片 that.fileList = fileList; if (index > -1) { that.fileList.splice(index, 1) } } else { let newArr = fileList.filter(item => item.name == file.name) let count = newArr.length; //删除重复数据 if(count > 1){ let index = fileList.indexOf(file) if (index > -1) { publicJS.showMessage("文件"+file.name+"已存在!", publicJS.ErrorType); fileList.splice(index, 1) } } that.fileList = fileList; } },
三、方法
// 判断文件的大小不超过10m,判重 handleChange(file,fileList){ this.$publicjs.uploadImageSize(this,file,fileList) }, // 删除文件 handleRemove(file,fileList) { this.fileList = fileList; if(file.id){ this.$confirm("确定要删除此文件吗,删除后不可恢复。",'提示',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' }).then(()=>{ deleteItemImg(file.id).then(res =>{ if(res.code==200){ this.$publicjs.showMessage(res.message, this.$publicjs.SuccessType); }else{ this.fileList.push(file); this.$publicjs.showMessage(res.message, this.$publicjs.ErrorType); } }) }).catch(()=>{ this.fileList.push(file); }) } }, // 预览图片 handlePreview(file) { this.dialogImageUrl = file.url this.dialogVisible = true },
四、带着图片一起保存
saveMethod() { this.$refs["form"].validate((valid) => { if (valid) { // 文件内容 let saveData = new FormData(); for (let i = 0; i < this.fileList.length; i++) { if (this.fileList[i].raw) { saveData.append("file", this.fileList[i].raw); } } for(let x in this.form){ if(this.form[x] != ""){ saveData.append(x,this.form[x]); } } if (this.form.id == "") { addData(saveData).then((res) => { if (res.code == 200) { this.$publicjs.showMessage(res.message, this.$publicjs.SuccessType); this.queryMethod(); this.isShowTable = true; this.isShowOrgTree = true; } else { this.$publicjs.showMessage(res.message, this.$publicjs.ErrorType); } }); } else { updateData(saveData).then((res) => { if (res.code == 200) { this.$publicjs.showMessage(res.message, this.$publicjs.SuccessType); this.queryMethod(); this.isShowTable = true; this.isShowOrgTree = true; } else { this.$publicjs.showMessage(res.message, this.$publicjs.ErrorType); } }); } this.fileList=[]; } }); },
五、调用后端接口方法
// 物品上传图片
export function getItemFile(params) {
return request({
url: 'api/sys-attach-filepath-info/query',
method: 'get',
params
})
}
// 删除单个物品图片
export function deleteItemImg(id) {
return request({
url: 'api/sys-attach-filepath-info/' + id,
method: 'delete'
})
}
// 添加
export function addData(data) {
return request({
url: 'api/sys-case-info/add',
method: 'post',
data
})
}
// 更新export function updateData(data) {
return request({
url: 'api/sys-case-info',
method: 'put',
data
})
}
六、后端接口--控制器
1、@ApiOperation(value = "查询分页数据") @ApiImplicitParams({ @ApiImplicitParam(name = "pageIndex", value = "页码"), @ApiImplicitParam(name = "pageCount", value = "每页条数"), @ApiImplicitParam(name = "relationId", value = "相关数据id") }) @GetMapping(value = "/query") public Response<String> findListByPage(@RequestParam(value = "page_index", required = false) Integer pageIndex, @RequestParam(value = "page_count") Integer pageCount, String relationId){}
2、删除图片
@ApiOperation(value = "删除")
@DeleteMapping("{id}")
public Response<Integer> delete(@PathVariable("id") String id){
int re = sysAttachFilepathInfoService.delete(id);
if (re > 0) {
return new Response<>(ErrorCode.SUCESS_CODE, "删除成功", re);
} else {
return new Response<>(ErrorCode.INTERNAL, "删除失败,未知错误", null);
}
}
3、保存
@ApiOperation(value = "新增")
@PostMapping(value = "/add")
public Response<Integer> add(SysCaseInfo sysCaseInfo,@RequestParam("file") MultipartFile[] files){}
4、更新
@ApiOperation(value = "更新")
@PutMapping()
public Response<Integer> update(SysCaseInfo sysCaseInfo,@RequestParam("file") MultipartFile[] files){}
七、后端接口-实现类
一、文件路径
public static String fileUpload(MultipartFile[] files, String id, String path,String tableName) {
String thumn = "";
try {
if (files != null && files.length > 0) {
File filePath = new File(path+tableName);
//判断filePath是否存在
if (!filePath.exists() && !filePath.isDirectory()) {
//filePath目录不存在,需要创建
filePath.mkdirs();
}
int len = files.length;
for (int i = 0; i < len; i++) {
//获取文件原始名称(带扩展名)
String originalFilename = files[i].getOriginalFilename();
//获取文件类型
String type = originalFilename.substring(originalFilename.lastIndexOf("."));
//生成新文件名称
String filename =tableName+"/"+ id + "_" + System.currentTimeMillis() + type;
byte[] bytes = files[i].getBytes();
File file1 = new File(path + filename);
if (file1.exists() && !file1.delete()) {
throw new Exception((path + filename) + "文件删除错误");
}
Path newpath = Paths.get(path + filename);
Files.write(newpath, bytes);
if (i < len - 1) {
thumn += filename + ",";
} else {
thumn += filename;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return thumn;
}
二、添加文件保存在表中
public void addFile(MultipartFile[] files, String id, String tableName) { // 图片列表 List<SysAttachFilepathInfo> fileList = new ArrayList<>(); //存储图片的路径 int count = files.length; if (files != null && count > 0) { String path = fileConfig.getFileServer(); String filepaths = FileUtil.fileUpload(files, id, path,tableName); //上传图片 String[] filepath = filepaths.split(","); for(int i = 0; i < filepath.length; i++){ SysAttachFilepathInfo info = new SysAttachFilepathInfo(); info.setId(SnowIdUtil.getId()); // 关联主键 info.setRelationId(id); // 关联表 info.setRelationTable(tableName); // 图片路径 info.setFilePath(filepath[i]); fileList.add(info); } // 如果有数据则保存 if(CollectionUtils.isNotEmpty(fileList)){ sysAttachFilepathInfoMapper.batchInsert(fileList); } } }
八、批量操作 xml文件
一、批量添加 <insert id="batchInsert" parameterType="com.hengan.involved.entity.SysAttachFilepathInfo"> INSERT INTO sys_attach_filepath_info (id, relation_table, relation_id,file_path) values <foreach collection="list" item="item" separator=","> (#{item.id}, #{item.relationTable}, #{item.relationId}, #{item.filePath}) </foreach> </insert>
二、批量更新
<update id="batchUpdate" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" separator=";">
UPDATE show_overview set item_num = #{item.itemNum} WHERE id=#{item.id}
</foreach>
</update>