{ "title": "<a-upload multiple accept="image/png, image/jpeg" :action="uploadImgURL" list-type="picture-card" :file-list="photo" @preview="handleImgPreview" @change="handleImgChange" > <div v-if="photo.length < 5" class="feed_upload" > <a-icon :type="'plus'" /> <div class="ant-upload-text">上传

data () { return { uploadImgURL: window._CONFIG['domainUrl']+"/sys/common/upload", } handleImgChange({ fileList }) { this.photo = fileList.slice(-4) }, compressAndUpload(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (event) { const img = new Image(); img.src = event.target.result; img.onload = function () { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const maxWidth = 800; // 设置压缩后的最大宽度 const maxHeight = 800; // 设置压缩后的最大高度 let targetWidth = img.width; let targetHeight = img.height; if (targetWidth > maxWidth || targetHeight > maxHeight) { if (targetWidth / targetHeight > maxWidth / maxHeight) { targetWidth = maxWidth; targetHeight = Math.round(maxWidth * (img.height / img.width)); } else { targetHeight = maxHeight; targetWidth = Math.round(maxHeight * (img.width / img.height)); } } canvas.width = targetWidth; canvas.height = targetHeight; ctx.clearRect(0, 0, targetWidth, targetHeight); ctx.drawImage(img, 0, 0, targetWidth, targetHeight); canvas.toBlob(function (blob) { const formData = new FormData(); formData.append('file', blob, file.name); fetch(window._CONFIG['domainUrl'] + '/sys/common/upload', { method: 'POST', body: formData, }) .then(response => response.json()) .then(data => resolve(data)) .catch(error => reject(error)); }, file.type || 'image/jpeg', 0.9); // 设置压缩质量,0.9表示90%质量 }; }; }; }, handleImgChange({ fileList }) { const compressedFiles = fileList.slice(-4).map(file => this.compressAndUpload(file)); Promise.all(compressedFiles) .then(response => { // 处理上传成功的结果 }) .catch(error => { // 处理上传失败的错误 }); }, }

JavaScript 图片压缩和上传到服务器 - 代码示例

原文地址: https://www.cveoy.top/t/topic/qepI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录