面向百度开发

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. 易位构词EOJ3451【字符串】【思维题】【模拟】

    http://acm.ecnu.edu.cn/problem/3451/ 官方题解: 我们可以先考虑字符串有序的情况,比如是 aaabcc,我们只要将字符串右移 3 位,变成 bccaaa,就做完了. ...

  2. php 正则学习取反符号~

    php 正则学习取反符号~ ~(<a .*?>.*?</a>|<.*?>)~i 先看正则图形,有点偏差,但可以初步看出结果. 关于 ~ 是取反符号,看下面说明.

  3. Java 调用restful webservice & jackson

    package com.bullshit.webcrawler.client.impl; import java.io.BufferedReader; import java.io.IOExcepti ...

  4. Vue电商后台管理系统项目第1天-基本环境搭建&登录功能

    基本环境搭建完成 安装npm包:npm -S i vue vue-router axios element-ui 配置Eslint: 打开设置,搜索Eslint拓展,然后将下面代码覆盖进去即可 { , ...

  5. CRT (C run-time library)

    一 产生 运行时库是程序在运行时所需要的库文件,通常以LIB或DLL形式提供. C运行时库就是C run-time library,诞生于20世纪70年代,是C而非C++语言世界的概念,C程序运行时需 ...

  6. 新浪微博API错误代码说明对照表 http://open.weibo.com/wiki/Error_code

    http://open.weibo.com/wiki/Error_code 这篇文章资料是从新浪微博开发平台分享过来,一方面是博主自己开发过程遇到问题对错误代码的快捷查询,不用每次都得到官方找:另一方 ...

  7. 2018-5-28-win10-uwp-动态修改ListView元素布局

    title author date CreateTime categories win10 uwp 动态修改ListView元素布局 lindexi 2018-05-28 15:15:54 +0800 ...

  8. HTML5有哪些新特性?移除了哪些元素?

    HTML5新特性: 拖放(Drag and drop)API 语义化标签(header.nav.footer.section.article.aside) 音频.视频(audio.video)API ...

  9. Project Euler Problem 7-10001st prime

    素数线性筛 MAXN = 110100 prime = [0 for i in range(210000)] for i in range(2,MAXN): if prime[i] == 0: pri ...

  10. H3C 对等通信