最近没事刚好联系下vue+springboot前段后分离的项目、用上了图片上传功能、记录一下。
前端待提交的表单部分代码
<el-form-item label="封面图片"> <el-upload v-model="dataForm.title" class="avatar-uploader" :limit="1" list-type="picture-card" :on-preview="handlePictureCardPreview" multiple :http-request="uploadFile" :on-remove="handleRemove" :on-change='changeUpload' :file-list="images"> <i class="el-icon-plus"></i> </el-upload> </el-form-item>
el-upload里面的元素解释:
- on-preview:点击文件列表中已上传的文件时的事件
- on-remove:删除文件时候调用的方法
- on-change:文件状态改变时的事件,添加文件、上传成功和上传失败时都会被调用
- file-list:上传的文件列表或者默认回显的数据展示渲染
retrun和data
return { images: [{name: 'food.jpg', url: 'https://img-blog.csdnimg.cn/20210329194832973.png'}], imageUrl: '', fileList: [], // 文件上传数据(多文件合一) dialogImageUrl: '', dialogVisible: false, options: [], content: '', editorOption: {}, visible: false, dataForm: { id: 0, title: '', content: '', bz: '' }, tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化 }
预览图片和上传图片以及删除图片
changeUpload: function(file, fileList) {//预览图片 this.fileList = fileList; }, uploadFile(file){ }, handleRemove(file, fileList) { }, handlePictureCardPreview(file) { this.dialogImageUrl = file.url; this.dialogVisible = true; },
这里我是用fomrData对象进行提交的、因为只需要上传一张单张封面图片、还有添加其他的一些表单内容进去
// 表单提交 dataFormSubmit () { const form = new FormData()// FormData 对象 form.append('file', this.fileList); form.append('title', this.dataForm.title); form.append('content', this.$refs.text.value); this.$refs['dataForm'].validate((valid) => { if (valid) { this.$http({ url: this.$http.adornUrl(`/sys/inform/${!this.dataForm.id ? 'save' : 'update'}`), method: 'post', data: form }).then(({data}) => { if (data && data.code === 0) { this.$message({ message: '操作成功', type: 'success', duration: 1500, onClose: () => { this.visible = false this.$emit('refreshDataList') } }) } else { this.$message.error(data.msg) } }) } }) }
后台的话通过HttpServletRequest request–WebUtils
.getNativeRequest(request, MultipartHttpServletRequest.class)来获取文件请求并解析文件到服务器或本地
/** * @author lyy * 保存 PC-后台上传文件 */ @RequestMapping(value = "sys/file/save", method = {RequestMethod.POST, RequestMethod.GET}) @Transactional public R save(HttpServletRequest request) { String classify = request.getParameter("classify"); MultipartHttpServletRequest multipartRequest = WebUtils .getNativeRequest(request, MultipartHttpServletRequest.class); String fileName = ""; if (multipartRequest != null) { Iterator<String> names = multipartRequest.getFileNames(); while (names.hasNext()) { List<MultipartFile> files = multipartRequest.getFiles(names.next()); if (files != null && files.size() > 0) { for (MultipartFile file : files) { fileName = file.getOriginalFilename(); String SUFFIX = FileUtil.getFileExt(fileName); File uFile = new File(); uFile.setFileName(fileName); uFile.setClassify(classify); uFile.setCreateTime(new Date()); uFile.setFileType(SUFFIX); String uuid = FileUtil.uuid(); try { uFile.setPath(uploadFile(uuid,file) +uuid+"."+SUFFIX); } catch (IOException e) { e.printStackTrace(); } fileService.save(uFile); } } } } return R.ok(); }
上传文件到本地的静态方法
/** * 上传文件 *@author lyy * @param file * @return * @throws IOException * @throws IllegalStateException */ public static String uploadFile(String uuid, MultipartFile file) throws IllegalStateException, IOException { String defaultUrl = MyFileConfig.getFilePath(); String Directory = java.io.File.separator ; String realUrl = defaultUrl + Directory; java.io.File realFile = new java.io.File(realUrl); if (!realFile.exists() && !realFile.isDirectory()) { realFile.mkdirs(); } String fullFile = realUrl + uuid + "."+FileUtil.getFileExt(file.getOriginalFilename()); file.transferTo(new java.io. File(fullFile)); String relativePlanUrl = Directory; return relativePlanUrl.replaceAll("\\", "/"); }
到此这篇关于Vue+Element+Springboot图片上传的实现示例的文章就介绍到这了,更多相关Vue+Element+Springboot图片上传内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!