官方 API 地址: https://developer.qiniu.com/kodo/sdk/1283/javascript
由于七牛提供了 JavaScript 上傳的插件,本文將采用該插件實現七牛直傳。
1. 獲取七牛上傳憑證
與阿里云OSS直傳不同的是,七牛只需要獲取一個
token
即可(本質是一樣的)。獲取需要后端的配合,提供一個接口。
要注意獲取和保存的時機,根據過期時間記錄相關
sessionStorage
比較好,既能減少請求的次數,又能保證上傳時憑證有效。獲取
token
流程:
(1)發送獲取 token
請求 --> (2)得到 token
并本地保存,用于之后的直傳 --> (3)帶著 token
參數向七牛發送請求,直傳圖片 --> (4) 上傳成功,七牛會返回相應的圖片地址(這個地址后續需要按照一定規則傳給后端)
- 獲取
token
示例
/**
* 獲取七牛圖片上傳 token (進入相關頁面預先請求)
* @returns {Promise.<T>}
*/
const getUploadToken = () => {
http.post('getUploadToken').then(res => {
if (res.code === 200) {
this.isPull = false;
const expireTime = 30 * 60 * 1000; // 過期時間,單位毫秒(ms)
sessionStorage.setItem('uploadToken', res.data.upload_token);
sessionStorage.setItem('uploadTokenExpireTime', new Date().getTime() + expireTime); // 設置 token 過期時間
sessionStorage.setItem('imgURL', res.data.image_url); // 暫存圖片地址
} else {
// 錯誤統一處理函數
this.errorHandler(res);
}
}).catch(() => {
console.log('error');
});
}
2. 圖片處理
- 這里即將使用的
qiniu.min.js
也包含了圖片裁剪、縮放、旋轉等功能。有興趣的可以看下這個文檔:七牛 - 圖片高級處理
這里介紹一下自己實現圖片的簡單處理。
(1) 壓縮圖片在 iOS 上存在一個旋轉的問題,需要先做處理,這里引入了 exif-js
import Exif from 'exif-js'
(2)圖片旋轉
/**
* iOS 旋轉圖片
* @param img 圖片
* @param direction 旋轉方向
* @param canvas 畫布
*/
const rotateImg = (img, direction, canvas) => {
// 最小與最大旋轉方向,圖片旋轉4次后回到原方向
const min_step = 0;
const max_step = 3;
if (img === null) return;
// img 的高度和寬度不能在 img 元素隱藏后獲取,否則會出錯
let height = img.height;
let width = img.width;
let step = 2;
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 * 90 * Math.PI / 180;
let ctx = canvas.getContext('2d');
switch (step) {
case 0:
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0);
break;
case 1:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, 0, -height);
break;
case 2:
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, -width, -height);
break;
case 3:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, 0);
break;
}
}
(3)圖片壓縮
/*
* canvas 壓縮圖片
* @param img 圖片
* @param Orientation 旋轉參數
* @returns ndata 壓縮后的數據
*/
const 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;
let time = new Date().getTime();
// 如果圖片大于四百萬像素,計算壓縮比并將大小壓至400萬以下
let ratio;
if ((ratio = width * height / 4000000) > 1) {
console.log("大于400萬像素");
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
} else {
ratio = 1;
}
canvas.width = width;
canvas.height = height;
// 鋪底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 如果圖片像素大于100萬則使用瓦片繪制
let count;
if ((count = width * height / 1000000) > 1) {
console.log("超過100W像素");
count = ~~(Math.sqrt(count) + 1); //計算要分成多少塊瓦片
// 計算每塊瓦片的寬和高
let nw = ~~(width / count);
let nh = ~~(height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for (let i = 0; i < count; i++) {
for (let j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
}
}
} else {
ctx.drawImage(img, 0, 0, width, height);
}
// 修復ios上傳圖片的時候 被旋轉的問題
if (Orientation != '' && Orientation != 1) {
switch (Orientation) {
case 6: // 需要順時針(向左)90度旋轉
this.rotateImg(img, 'left', canvas);
break;
case 8: // 需要逆時針(向右)90度旋轉
this.rotateImg(img, 'right', canvas);
break;
case 3: // 需要180度旋轉
this.rotateImg(img, 'right', canvas);//轉兩次
this.rotateImg(img, 'right', canvas);
break;
}
}
// 進行最小壓縮
let ndata = canvas.toDataURL('image/jpeg', 0.1);
console.log('壓縮前:' + initSize);
console.log('壓縮后:' + ndata.length);
console.log('壓縮率:' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
console.log('使用時間:' + (new Date().getTime() - time) + 'ms');
return ndata;
}
(4) 將 base64 圖片編碼轉為 Blob 對象
/*
* 將 base64 圖片編碼轉為 Blob 對象
* @dataURI 圖片 base64 編碼
* @returns {Blob}
*/
const dataURItoBlob = (dataURI) => {
let byteString = atob(dataURI.split(',')[1]);
let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {type: mimeString});
}
3. 七牛上傳方法
(1)引入七牛
import * as qiniu from 'qiniu-js'
(2)上傳方法
/**
* 七牛上傳
* @param base64String 文件信息(Blob 或 base64String)
*/
const qiniuUpload = (base64String) => {
// 由于有些大圖進行壓縮后變成了 base64String,而小圖沒有經過處理仍是 Blob 對象,七牛接收的參數是 Blob 對象,故對字符串類型的參數進行轉換
let file;
if (typeof base64String === 'string'){
file = this.dataURItoBlob(base64String);
} else {
file = base64String;
}
// 七牛上傳的方法
// 第一個參數是文件對象(Blob),第二個參數是文件名稱(這個名稱不能相同,命名時候請加入時間搓,確保文件名稱唯一),第三個參數是 token
const observable = qiniu.upload(file, file.name, sessionStorage.getItem('uploadToken'), {
fname: file.name,
params: {},
mimeType: [] || null
}, {
useCdnDomain: true, // cdn
unique_names: false, // 唯一名稱
region: qiniu.region.z0 // 根據區域設置上傳的域名
});
// 返回 Promise,在里面執行七牛直傳
return new Promise( (resolve, reject) => {
const subscription = observable.subscribe({
next (res) {
// 上傳的進度,可以獲得總大小,已傳大小,上傳百分比進度
},
error (err) {
console.log('失敗');
console.log(err);
},
complete (res) {
// 成功后,回調操作
console.log('上傳成功');
resolve({
base64String: base64String,
imgUrl: sessionStorage.getItem('imgURL')+'/'+ res.key
});
}
});
});
}
4. 前面所做的都是準備工作,真正觸發上傳的在這里
/*
* 讀文件(<input type="file"> 由 change 事件觸發)
* @param file 文件 Blob 對象,由 change 事件觸發后傳入該參數
* @returns {Promise}
*/
const readFiles = (file) => {
// 首先判斷 token 是否過期
async function getToken() {
if (new Date().getTime() > sessionStorage.getItem('uploadTokenExpireTime')) {
getUploadToken();
}
}
return getToken().then(() => {
let Orientation;
let base64String = '';
const reader = new FileReader(); // 創建 FileReader 對象 并調用 render 函數來完成渲染
// 將圖片將轉成 base64 格式
base64String = reader.readAsDataURL(file);
// iOS 旋轉問題
Exif.getData(file, function () {
Orientation = Exif.getTag(this, 'Orientation');
});
// 讀取后壓縮文件
return new Promise(resolve => {
reader.onloadend = function () {
let result = this.result;
let img = new Image();
img.src = result;
//判斷圖片是否大于100K,是就直接上傳,反之壓縮圖片
if (this.result.length <= (100 * 1024)) {
resolve(qiniuUpload(result));
} else {
img.onload = function () {
let data = that.compress(img, Orientation);
resolve(that.qiniuUpload(data));
}
}
};
});
});
}
在低版本瀏覽器使用上存在一定的兼容問題;
上面的方法使用了 es6 語法;
上面的方法不能搬來直接使用,需要做一點小改動。