Vue+axios+formdata实现多张图片上传
<p>选择图片附件</p><div class="upload"><div class="upload_warp_left" @click="fileClick" ><button class="btn
<p>选择图片附件</p> <div class="upload"> <div class="upload_warp_left" @click="fileClick" > <button class="btn btn-success">上传图片</button> </div> <div class="upload_warp_text"> 已选中{{imgList.length}}张图片 </div> <div class="upload_warp" style="border: 1px solid white;"> <div class="upload_warp_img" v-show="imgList.length!=0" > <div class="upload_warp_img_div" v-for="(item,index) of imgList" > <div class="upload_warp_img_div_top" > <div class="upload_warp_img_div_text" > {{item.file.name}} </div> <img src="../../../static/images/delete.png" class="upload_warp_img_div_del" @click="fileDel(index)"> </div> <img :src="item.file.src"> </div> </div> </div> <input type="file" id="files" ref="files" multiple v-on:change="handleFilesUpload($event)" style="display: none"/> <!-- <input v-on:change="fileChange()" ref="files" type="file" id="files" multiple />--> </div>
样式 .upload_warp_img_div_del { position: absolute; top: 6px; width: 16px; right: 4px; } .upload_warp_img_div_top { position: absolute; top: 0; width: 100%; height: 30px; background-color: rgba(0, 0, 0, 0.4); line-height: 30px; text-align: left; color: #fff; font-size: 12px; text-indent: 4px; } .upload_warp_img_div_text { white-space: nowrap; width: 80%; overflow: hidden; text-overflow: ellipsis; } .upload_warp_img_div img { max-width: 100%; max-height: 100%; vertical-align: middle; } .upload_warp_img_div { position: relative; height: 100px; width: 120px; border: 1px solid #ccc; margin: 0px 5px 5px 0px; float: left; line-height: 100px; display: table-cell; text-align: center; background-color: #eee; cursor: pointer; } .upload_warp_img { padding: 5px 0 0 5px; overflow: hidden } .upload_warp_text { text-align: left; margin-bottom: 5px; padding-top: 5px; text-indent: 14px; border-top: 1px solid #ccc; font-size: 14px; } .upload_warp_right { float: left; width: 57%; margin-left: 2%; height: 100%; border: 1px dashed #999; border-radius: 4px; line-height: 130px; color: #999; } .upload_warp_left button { margin: 8px 5px 0px 5px; cursor:pointer; } .upload_warp_left { float: left; } .upload_warp { margin: 5px; } .upload { border-left: 1px solid #ccc; border-right: 1px solid #ccc; background-color: #fff; box-shadow: 0px 1px 0px #ccc; border-radius: 4px; }
定义全局的formdata
let formData; export default {
} mounted () { this.formData = new FormData(); },
methods:{ addIrrInfor(){ //上传按钮 let config = { headers: { 'Content-Type': 'multipart/form-data' //之前说的以表单传数据的格式来传递fromdata } }; formData.append('a','aa'); //appeend其他参数 this.$axios.post(上传地址,formData,config ).then((response) => { if(response.data.stateCode === 200){ alert("成功") } }) .catch((error) =>{ console.log(error); }); }, fileClick(){ //点击选择图片按钮 document.getElementById('files').click() }, handleFilesUpload(el){ //一定要在这选择一次时,append一次 this.filesArr=this.$refs.files.files //console.log(this.filesArr) for( var i = 0; i < this.filesArr.length; i++ ){ formData.append('file',this.filesArr[i]); } if (!el.target.files[0].size) return; this.fileList(el.target.files); }, fileList(files){ for (let i = 0; i < files.length; i++) { this.fileAdd(files[i]); } }, fileAdd(file){ this.size = this.size + file.size;//总大小 let reader = new FileReader(); reader.vue = this; reader.readAsDataURL(file); reader.onload = function () { file.src = this.result; this.vue.imgList.push({ file }); } }, fileDel(index){ //删除已选择的图片 this.size = this.size - this.imgList[index].file.size;//总大小 this.imgList.splice(index, 1); }, },
后端代码:
public void saveComplaintInfo(ComplaintInfo complaint, List<MultipartFile> file, HttpServletRequest request) {
complaint.setId(UUID.randomUUID().toString());
complaint.setCreate_time(DateUtils.DateFormatUnit.DATE_TIME.getDateStr(new Date()));
complaint.setJk_allocate_status(0);
complaint.setGu_allocate_status(0);
complaint.setProcess_status(0);
String url = ""; //保存的文件名
for(MultipartFile picture: file){
String orgFileName = picture.getOriginalFilename();
String sname = orgFileName.substring(orgFileName.lastIndexOf("."));
String id= UUID.randomUUID().toString()+sname;
// File saveFile = new File(request.getSession().getServletContext().getRealPath("/upload/") + id);
File saveFile = new File("/home/file/"+ id);
// File saveFile = new File("E:/"+ id);
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
url += id + ",";
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
out.write(picture.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(!url.equals("")){
url.substring(0,url.length()-1); //去除最后一个逗号
}
complaint.setPicture_name(url);
complaintDao.save(complaint);
}
@RequestMapping("/saveComplaintInfo")
@ResponseBody
public JSONObject saveComplaintInfo(ComplaintInfo complaint, @RequestParam(value = "file",required = false) List<MultipartFile> file, HttpServletRequest request, HttpServletResponse response) {
ResultOMUI result = new ResultOMUI(CommUtils.SUCCODE);
response.setContentType("text/html;charset=utf-8");
try{
//@RequestBody ComplaintInfo complaint,
// ComplaintInfo complaint = new ComplaintInfo();
// complaint.setComplaint_title("测试");
complaintService.saveComplaintInfo(complaint,file,request);
result.setData("");
result.setMessage("新增成功");
}catch(Exception e){
result.setData("服务器错误");
result.setStateCode(CommUtils.ERRCODE);
LOGGER.error(new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date()) + "--保存用户信息失败!", e.getMessage());
}
return JSONObject.fromObject(result);
}
更多推荐
所有评论(0)