赞
踩
el-upload
放到一个el-form里面,点击保存才提交,所以不能直接用action的方式,下面采用自定义上传的方式来完成editForm.imgList
来保存图片的信息,注意这里是一个对象,其格式如下我这里后端传回来的是一个字符串数组,把他转为对象如下
this.editForm.imgList = row.imgList.map((url,index) => ({
name:index,
url: url,
}));
前端主要代码
<el-form> <el-form-item label="描述" prop="description"> <el-input type="textarea" :rows="6" v-model="editForm.description" auto-complete="off" placeholder="请输入描述"></el-input> </el-form-item> <el-form-item label="图片" prop="description"> <el-upload action="" list-type="picture-card" multiple :on-change="handlChange" :file-list="editForm.imgList" :on-error="handleErr" ref="upload" :auto-upload="false"> <i slot="default" class="el-icon-plus"></i> <div slot="file" slot-scope="{file}"> <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" > <span class="el-upload-list__item-actions"> <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)" > <i class="el-icon-zoom-in"></i> </span> <span class="el-upload-list__item-delete" @click="handleRemove(file)" > <i class="el-icon-delete"></i> </span> </span> </div> </el-upload> </el-form-item> </el-form>
data() { return { editForm: { imgList: [], }, } methods: { handleRemove(file) { let arr = this.$refs.upload.uploadFiles // 2.从pics数组中,找到图片对应的索引值 let index = arr.indexOf(file) // 3.调用splice方法,移除图片信息 arr.splice(index, 1) }, handlePictureCardPreview(file) { this.dialogImageUrl = file.url; this.dialogVisible = true; }, handlChange(file, fileList) { this.editForm.imgList = fileList; console.log("change",this.editForm.imgList) }, submitForm() { let formData = new FormData(); // 用FormData存放上传文件 //将图片转为FormData格式 //formData.append() 方法向 FormData 对象添加同一个键(key)的多个值时, //实际上是在创建一个值的列表,而这个键会与每个添加的值关联起来, //后端接收到的就是一个List this.editForm.imgList.forEach(file => { console.log(file.raw) console.log(file.size) formData.append('files', file.raw) }) console.log(formData) //自定义上传 axios({ method: "post", url: "http://localhost:8089/upload", headers: { 'Content-Type': 'multipart/form-data', token: localStorage.getItem('logintoken') }, data:formData // traditional: true, }).then(function (res){ // console.log(res) return res; });//相当于function(res){ret }
@RestController @CrossOrigin public class ManageController { @Value("${saveimg.location.attractions}") String attractionLocation; @RequestMapping(value = "upload") public void uploadImg(@RequestParam("files") List<MultipartFile> files){ System.out.println("files = " + files); for (MultipartFile file : files) { if (!file.isEmpty()) { try { // 构建真实的文件路径 Path path = Paths.get(attractionLocation + file.getOriginalFilename()); // 确保目录路径存在 Files.createDirectories(path.getParent()); // 将上传文件保存到指定位置 file.transferTo(path); // 或者使用这种方式 // byte[] bytes = file.getBytes(); // Files.write(path, bytes); System.out.println("保存成功"); } catch (IOException e) { e.printStackTrace(); System.out.println( "上传失败"); } } else { System.out.println("失败"); } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。