直接贴代码了
使用的是vantUI框架,不过没有关系,都是对文件流进行判断压缩的。按需求改造一下就OK了
<template> <div class="page_publish"> <div class="bg_box"> <div class="form_box"> <div class="con"> <textarea class="textarea" v-model="formData.story" placeholder="经历了哪些有趣、快乐、感动的小故事...... ,写下来分享给我们吧" ></textarea> <div class="file_box"> <van-uploader :before-read="beforeRead" :after-read="afterRead" v-model="fileList" multiple :max-count="3" > <div class="upload_btn flex flex-v flex-align-center flex-pack-center"> <img src="../assets/imgs/icon_camaro.png" class="icon" /> <p class="num" v-if="fileList.length==0">添加图片</p> <p class="num" v-else>({{fileList.length}}/3)</p> </div> </van-uploader> </div> <p class="limit_txt">(限20-200字)</p> </div> <!-- 姓名手机号 --> <div class="contact_box"> <input type="text" placeholder="请输入您的姓名" v-model="formData.name" class="input" /> <input style="margin-top:0.30rem;" type="number" placeholder="请输入您的手机号" class="input" v-model="formData.phone" /> <span :to="{path:'/publish'}" @click="checkForm()" class="btn flex flex-align-center flex-pack-center" >书写故事</span> </div> </div> </div> <!-- 确认弹框 --> <div v-show="dialogSubmit" class="dialog_submit flex-v flex felx-align-center flex-pack-center"> <div class="con"> <p class="txt"> 确认文字、图片和个人信息无误 ? <br />ps:不要让大奖联系不到你哦~ </p> <div class="btn_box flex flex-align-center flex-pack-justify"> <button class="btn btn_l van-hairline--surround" @click="dialogSubmit=false;statistics3()" >我再改改</button> <button class="btn btn_r" @click="submit()">确认提交</button> </div> </div> </div> </div> </template> <script> import { checkLogin } from "../assets/js/util.js"; import { imgUpload, addStory } from "../http/api.js"; import urlConfig from "../http/env.js"; import Vue from "vue"; import { Button, Toast, Dialog, Loading, ImagePreview, Uploader, Divider } from "vant"; Vue.use(Toast, ImagePreview); export default { data() { return { formData: { story: "果图片 URL 中不包含类型信息,可以添加 isImage 标记来声明果图片 URL 中不包含类型信息,可以添加 isImage 标记来声明", name: "ss", phone: "13344443333", images: "" }, dialogSubmit: false, //确认弹框 fileList: [ // Uploader 根据文件后缀来判断是否为图片文件 // 如果图片 URL 中不包含类型信息,可以添加 isImage 标记来声明 ] }; }, mounted() { }, components: { [Uploader.name]: Uploader, [Divider.name]: Divider, [Loading.name]: Loading }, methods: { // 确认提交 submit() { let _this = this; this.dialogSubmit = false; this.statistics2(); Toast.loading({ message: "提交中...", forbidClick: true, duration: 0 }); this.unLoadImg() .then(res => { console.log(res); let params = { images: res, // 图片地址 ---非必填 string 多个地址之间用,号分隔 name: this.formData.name, // 用户姓名---必填 string phone: this.formData.phone, // 用户号码---必填 string story: this.formData.story, // 文字内容---必填 string headUrl: this.headUrl, nickname: this.nickName }; addStory(params).then(res => { console.log(res); this.clearForm(); Toast.clear(); Toast.success("提交成功,内容审核中!"); setTimeout(function() { _this.$router.go(-1); }, 1500); }); }) .catch(err => { console.log(err); Toast.clear(); Toast(err); }); },// 上传图片 unLoadImg() { let _this = this; let fileList = this.fileList; return new Promise(function(resolve, reject) { if (fileList.length == 0) { //没有图片 resolve(""); } else { // 有图片,上传 let formData = new FormData(); let files = fileList.forEach(function(item, i) { console.log(_this.convertBase64UrlToBlob(item.content)); // formData.append('images',item.file) //不压缩上传 formData.append( "images", _this.convertBase64UrlToBlob(item.content), "file_" + Date.parse(new Date()) + ".jpg" ); // 文件对象 }); imgUpload(formData) .then(res => { if (res.code == "PY0000") { resolve(res.response.imageUrl); } else { reject(res.msg); } }) .catch(err => { reject("图片上传失败"); }); } }); }, /** * 将以base64的图片url数据转换为Blob * 用url方式表示的base64图片数据 */ convertBase64UrlToBlob(urlData) { var arr = urlData.split(","), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); }; return new Blob([u8arr], { type: mime }); }, // 返回布尔值 beforeRead(file) { // console.log(file); if (file.type !== "image/jpeg" && file.type !== "image/png") { Toast("请上传 jpg/png 格式图片"); return false; } else if (file.size > 1024 * 1024 * 4) { Toast("图片大小不可超过4M!"); return false; }; return true; }, afterRead(file) { let _this = this; // 如果图片大小超过2M,则先压缩 if(file.file.size > 1024 * 1024 * 2){ var ready = new FileReader(); /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/ ready.readAsDataURL(file.file); ready.onload = function() { var re = this.result; _this.canvasDataURL(re); }; } }, // 压缩图片 canvasDataURL(path, obj, callback) { let _this = this; var img = new Image(); img.src = path; img.onload = function() { var that = this; // 默认按比例压缩 var w = that.width, h = that.height, scale = w / h; w = w; h = w / scale; var quality = 0.5; // 默认图片质量为0.5 //生成canvas var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); // 创建属性节点 var anw = document.createAttribute("width"); anw.nodeValue = w; var anh = document.createAttribute("height"); anh.nodeValue = h; canvas.setAttributeNode(anw); canvas.setAttributeNode(anh); ctx.drawImage(that, 0, 0, w, h); // quality值越小,所绘制出的图像越模糊 var base64 = canvas.toDataURL("image/jpeg", quality); // 回调函数返回base64的值 let length = _this.fileList.length; _this.fileList[length-1].content = base64; }; }, } }; </script>