面向百度开发

html

 <van-uploader :after-read="onRead" accept="image/*">
<img src="./icon_input_add.png" />
</van-uploader>

js

data() {
return {
files: {
name: "",
type: ""
},
headerImage: null,
picValue: null,
upImgUrl,
}
},
// 组件方法 获取 流
async onRead(file) {
// console.log(file);
// console.log(file.file);
this.files.name = file.file.name; // 获取文件名
this.files.type = file.file.type; // 获取类型
this.picValue = file.file; // 文件流
this.imgPreview(this.picValue);
},
// 处理图片
imgPreview(file) {
let self = this;
let Orientation;
//去获取拍照时的信息,解决拍出来的照片旋转问题
Exif.getData(file, function () {
Orientation = Exif.getTag(this, "Orientation");
});
// 看支持不支持FileReader
if (!file || !window.FileReader) return;
if (/^image/.test(file.type)) {
// 创建一个reader
let reader = new FileReader();
// 将图片2将转成 base64 格式
reader.readAsDataURL(file);
// 读取成功后的回调
reader.onloadend = function () {
// console.log(this.result);
let result = this.result;
let img = new Image();
img.src = result;
//判断图片是否大于500K,是就直接上传,反之压缩图片
if (this.result.length <= * ) {
self.headerImage = this.result;
self.postImg();
} else {
img.onload = function () {
let data = self.compress(img, Orientation);
self.headerImage = data;
self.postImg();
};
}
};
}
},
// 压缩图片
compress(img, Orientation) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
//瓦片canvas
let tCanvas = document.createElement("canvas");
let tctx = tCanvas.getContext("2d");
// let initSize = img.src.length;
let width = img.width;
let height = img.height;
//如果图片大于四百万像素,计算压缩比并将大小压至400万以下
let ratio;
if ((ratio = (width * height) / ) > ) {
// console.log("大于400万像素");
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
} else {
ratio = ;
}
canvas.width = width;
canvas.height = height;
// 铺底色
ctx.fillStyle = "#fff";
ctx.fillRect(, , canvas.width, canvas.height);
//如果图片像素大于100万则使用瓦片绘制
let count;
if ((count = (width * height) / ) > ) {
// console.log("超过100W像素");
count = ~~(Math.sqrt(count) + ); //计算要分成多少块瓦片
// 计算每块瓦片的宽和高
let nw = ~~(width / count);
let nh = ~~(height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for (let i = ; i < count; i++) {
for (let j = ; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, , , nw, nh);
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
}
}
} else {
ctx.drawImage(img, , , width, height);
}
//修复ios上传图片的时候 被旋转的问题
if (Orientation != "" && Orientation != ) {
switch (Orientation) {
case : //需要顺时针(向左)90度旋转
this.rotateImg(img, "left", canvas);
break;
case : //需要逆时针(向右)90度旋转
this.rotateImg(img, "right", canvas);
break;
case : //需要180度旋转
this.rotateImg(img, "right", canvas); //转两次
this.rotateImg(img, "right", canvas);
break;
}
}
//进行最小压缩
let ndata = canvas.toDataURL("image/jpeg", 0.1);
tCanvas.width = tCanvas.height = canvas.width = canvas.height = ;
return ndata;
},
// 旋转图片
rotateImg(img, direction, canvas) {
//最小与最大旋转方向,图片旋转4次后回到原方向
const min_step = ;
const max_step = ;
if (img == null) return;
//img的高度和宽度不能在img元素隐藏后获取,否则会出错
let height = img.height;
let width = img.width;
let step = ;
if (step == null) {
step = min_step;
}
if (direction == "right") {
step++;
//旋转到原位置,即超过最大值
step > max_step && (step = min_step);
} else {
step--;
step < min_step && (step = max_step);
}
//旋转角度以弧度值为参数
let degree = (step * * Math.PI) / ;
let ctx = canvas.getContext("2d");
switch (step) {
case :
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, , );
break;
case :
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, , -height);
break;
case :
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, -width, -height);
break;
case :
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, );
break;
}
},
//将base64转换为文件
dataURLtoFile(dataurl) {
var arr = dataurl.split(","),
bstr = atob(arr[]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], this.files.name, {
type: this.files.type
});
},
//这里写接口
async postImg() {
let file = this.dataURLtoFile(this.headerImage);
let formData = new window.FormData();
formData.append("file", file);
toast_loding(this, "图片上传中···");
try {
let res = await util.ajax.post(this.upImgUrl, formData, {
headers: {
"Content-Type": "multipart/form-data"
}
});
} catch (e) {
console.log(e);
}
}

记录走过的路,踩过的坑,互勉。

  前端交流群:87709616

有不同意见的可以留言,我们一起讨论。

参考:https://www.cnblogs.com/lvshaonan/p/8547676.html

土旦:移动端 Vue+Vant 的Uploader 实现 :上传、压缩、旋转图片的更多相关文章

  1. Web Uploader文件上传插件

    http://www.jq22.com/jquery-info2665   插件描述:WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现 ...

  2. Web Uploader文件上传&&使用webupload有感(黄色部分)

    引入资源 使用Web Uploader文件上传需要引入三种资源:JS, CSS, SWF. <!--引入CSS--> <link rel="stylesheet" ...

  3. 解决Web Uploader上传文件和图片 延迟和not defined

    1.出现list not define时,var $list = $("#fileList"); 2.选择文件框有延迟,可能是因为选择文件类型过多 mimeTypes: 'imag ...

  4. PHP服务端如何通过程序将图上传到指定的图片服务器与图片服务器的优化方案

    一:PHP服务端如何通过程序将图上传到指定的图片服务器与图片服务器的优化方案 (1) php服务器把图片处理成缩率图或指定大小的图片在通过PHP程序代码 操作FTP 上传到图片服务器. 二:图片服务器 ...

  5. mui plus.uploader.createUpload 上传文件服务端获取文件名中文乱码问题

    客户端上传文件需要做一次url编码:encodeURIComponent(fileName) 服务端:URL解码 var fileName = HttpUtility.UrlDecode(hfc.Fi ...

  6. Fine Uploader文件上传组件

    最近在处理后台数据时需要实现文件上传.考虑到对浏览器适配上采用Fine Uploader. Fine Uploader 采用ajax方式实现对文件上传.同时在浏览器中直接支持文件拖拽[对浏览器版本有要 ...

  7. HTML5文件上传器,纯脚本无插件的客户端文件上传器---Uploader 文件上传器类

    概述 客户端完全基于JavaScript的 浏览器文件上传器,不需要任何浏览器插件,但需要和jQuery框架协同工作,支持超大文件上传,其算法是将一个超大文件切片成N个数据块依次提交给服务 端处理,由 ...

  8. Wince 6.0适用 .NET 使用HttpRequest的Post上传文件,服务端的Web API接收Post上传上来的文件 代码

    //调用的示例 private string fileName = "InStorageData.csv"; string filePath = parentPath + Comm ...

  9. vue中使用axios post上传头像/图片并实时显示到页面

    在前端开发中,为了更好的用户体验,在头像上传时会先将图片显示到页面然后点击保存按钮 完成图片的上传成功 代码部分有参考他人的写法. html代码:   <div id="myPhoto ...

随机推荐

  1. HTML5环形音乐播放器

    在线演示 本地下载

  2. WPF TextBox提示文字设定

    WPF TextBox框提示文字,鼠标划入提示文字消失 <TextBox Width=" VerticalContentAlignment="Center" Bor ...

  3. UVA_694:The Collatz Sequence

    Language: C++ 4.8.2 #include<stdio.h> int main(void) { long long int m, n, copy_m; ; ; ) { sca ...

  4. UVa 10285【搜索】

    UVa 10285 哇,竟然没超时!看网上有人说是记忆化搜索,其实不太懂是啥...感觉我写的就是毫无优化的dfs暴力....... 建立一个坐标方向结构体数组,每个节点dfs()往下搜就好了. #in ...

  5. python 字符串(str)

  6. sum(),max(),avg(),RATIO_TO_REPORT()--分组统计

    select id,area, sum(1) over() as 总记录数, sum(1) over(partition by id) as 分组记录数, sum(score) over() as 总 ...

  7. SDUT-2117_数据结构实验之链表二:逆序建立链表

    数据结构实验之链表二:逆序建立链表 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 输入整数个数N,再输入N个整数,按照 ...

  8. css浮动规则

    1.浮动元素会从文档正常流中删除,但它仍会影响布局 2.浮动非替换元素必须为其指定width,否则元素的width会趋于0而导致浮动元素不能完整显示3.一旦元素具有了浮动属性,它便成为了一个块级元素. ...

  9. corn表达式——用于设置定时任务[转载]

    原文地址https://blog.csdn.net/xiaopihai86/article/details/50756306 http://www.cronmaker.com/  cron表达式验证网 ...

  10. 2019-8-31-dotnet-通过-WMI-获取设备厂商

    title author date CreateTime categories dotnet 通过 WMI 获取设备厂商 lindexi 2019-08-31 16:55:59 +0800 2019- ...