上一篇 Vue +Element UI +vue-quill-editor 富文本編輯器及插入圖片自定義 主要是寫了富文本編輯器的自定義及編輯器中圖片的上傳并插入到編輯內容,這篇文章單獨介紹一下element UI 圖片上傳控件的使用。首先要安裝element并中引入,安裝引入過程這里不再贅述。
1.引用element 上傳控件。
<el-upload action="/mgr/common/imgUpload"http://這里需要配置一下文件上傳地址(跨域) list-type="picture-card" accept="image/*" :limit="imgLimit" :file-list="productImgs" :multiple="isMultiple" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-exceed="handleExceed" :on-error="imgUploadError"> <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog>
2.js
export default { data() { return { dialogImageUrl: '', dialogVisible: false, productImgs: [], isMultiple: true, imgLimit: 6 } }, methods: { handleRemove(file, fileList) {//移除圖片 console.log(file, fileList); }, handlePictureCardPreview(file) {//預覽圖片時調用 console.log(file); this.dialogImageUrl = file.url; this.dialogVisible = true; }, beforeAvatarUpload(file) {//文件上傳之前調用做一些攔截限制 console.log(file); const isJPG = true; // const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; // if (!isJPG) { // this.$message.error('上傳頭像圖片只能是 JPG 格式!'); // } if (!isLt2M) { this.$message.error('上傳圖片大小不能超過 2MB!'); } return isJPG && isLt2M; }, handleAvatarSuccess(res, file) {//圖片上傳成功 console.log(res); console.log(file); this.imageUrl = URL.createObjectURL(file.raw); }, handleExceed(files, fileList) {//圖片上傳超過數量限制 this.$message.error('上傳圖片不能超過6張!'); console.log(file, fileList); }, imgUploadError(err, file, fileList){//圖片上傳失敗調用 console.log(err) this.$message.error('上傳圖片失敗!'); } } }3.controller
@RequestMapping(value = "/imgUpload") public Wrapper imgUpload(HttpServletRequest req, MultipartHttpServletRequest multiReq) throws IOException { System.out.println("---" + fileUploadPath);//我這里用的springboot 在application.properties中配置,使用@Value 獲取的文件上傳目錄 MultipartFile file = multiReq.getFile("file"); String originalFilename = file.getOriginalFilename(); String suffix = originalFilename.substring(originalFilename.indexOf(".")); String localFileName = MD5Util.md5(file.getInputStream()) + suffix; File localFile = new File(fileUploadPath + localFileName); if (!localFile.exists()) { localFile.createNewFile(); FileOutputStream fos = new FileOutputStream( localFile); FileInputStream fs = (FileInputStream) multiReq.getFile("img").getInputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = fs.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); fs.close(); } else { log.info("文件已存在!!"); } return WrapMapper.wrap( Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, "http://localhost:8080/img/" + localFileName);//這里是我執行封裝的返回結果,也可以使用map, }
新聞熱點
疑難解答
圖片精選