vue 文件file上传前压缩大小

本文介绍了如何在Vue.js项目中创建一个公共JS文件,用于在文件上传前对其进行压缩,以减少上传的数据大小。
摘要由CSDN通过智能技术生成
1.先建立一个公共的js文件
//base64转码(压缩完成后的图片为base64编码,这个方法可以将base64编码转回file文件)
function dataURLtoFile(dataurl) {
   
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
   
    u8arr[n] = bstr.c
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用一些库或工具来压缩图片大小,然后再进行文件上传。以下是一种常见的方法: 1. 首先,您可以使用`HTML5 Canvas`来进行图片的压缩。您可以将图像绘制到一个临时的Canvas中,然后在导出之调整其尺寸。这可以通过以下步骤实现: ```javascript function compressImage(file, maxWidth, maxHeight, quality) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function (event) { const img = new Image(); img.src = event.target.result; img.onload = function () { const canvas = document.createElement('canvas'); let width = img.width; let height = img.height; if (width > height) { if (width > maxWidth) { height *= maxWidth / width; width = maxWidth; } } else { if (height > maxHeight) { width *= maxHeight / height; height = maxHeight; } } canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); canvas.toBlob(function (blob) { resolve(blob); }, file.type, quality); }; }; reader.onerror = function (error) { reject(error); }; reader.readAsDataURL(file); }); } ``` 上述函数`compressImage`接受四个参数:`file`为要压缩的图片文件,`maxWidth`和`maxHeight`为期望的最大宽度和高度,`quality`为压缩质量(0-1之间的值,1表示最高质量)。 2. 然后,您可以使用`axios`或其他网络请求库将压缩后的图片文件上传到服务器。 ```javascript const formData = new FormData(); formData.append('file', compressedImageFile); axios.post('/upload', formData) .then(response => { console.log('上传成功'); }) .catch(error => { console.error('上传失败', error); }); ``` 上述代码将压缩后的图片文件添加到`FormData`对象中,然后使用`axios.post`方法将其上传到服务器的`/upload`接口。 请注意,以上代码仅为示例,您可能需要根据您的具体需求进行适当调整。另外,您还可以使用其他基于Canvas的图片处理库或基于HTML5 File API的库来完成相同的任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值