VUE集成Cos騰訊圖片服務器


安裝 npm install --save cos-js-sdk-v5   spark-md5

 

<el-upload
class="upload-demo"
:file-list="newImages"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="handleAvatarSuccess"
:before-remove="beforeRemove"
:before-upload="beforeAvatarUpload">
<el-button size="small" type="primary">點擊上傳</el-button>
</el-upload>
import uploadFile from '../../util/uploadFile'
const bannerOptions = [{
type: 'image/jpeg',
size: 10
}, {
type: 'image/png',
size: 10
}]
beforeAvatarUpload (file) {
let that = this
// console.log('before',that.imgList)
// 顯示loading動畫
this.imgUpdateImg = true
let isJPG = false
let isLt2M = false
let fileSize = 0
for (let option of bannerOptions) {
if (option.type === file.type) {
isJPG = true
fileSize = option.size
if (option.size > file.size / 1024 / 1024) {
isLt2M = true
}
}
}
if (!isJPG) {
that.$message.error('上傳的圖片只能是 jpg/png 格式')
that.imgUpdateImg = false
}
if (!isLt2M) {
that.$message.error('上傳文件的大小不能超過 ' + fileSize + 'MB!')
that.imgUpdateImg = false
}
this.selectFile(file)
return isJPG && isLt2M
},

selectFile (event) {
console.log(event)
// console.log('selectFile', event.target.files[0].name)
// 調用上傳方法,傳入選擇的文件對象
// this.uploadFile(event.target.files[0], () => {
// console.log('ckckckckckckckckckckk')
// })
// console.log('selectFile', event.target.files[0])
uploadFile(event, (key) => {
console.log(key)
this.newImages.push(key)
console.log(this.newImages)
})
uploadFile.js 文件

import Vue from 'vue'
import SparkMD5 from 'spark-md5'
import { cosConfig } from './config'
import COS from 'cos-js-sdk-v5'

export default function(file,backtopage) {
var key = ''
Vue.prototype.uploadFile = uploadFile
console.log('hhhhhhhhhhhhhhhhhhhhhhhhh')
console.log(cosConfig)
var cos = new COS({
getAuthorization: function (params, callback) {//獲取簽名 必填參數
// 方法二(適用於前端調試)
var authorization = COS.getAuthorization({
SecretId: cosConfig.SecretId,
SecretKey: cosConfig.SecretKey,
Method: params.Method,
Key: params.Key
});
callback(authorization);
}
});
console.log(cos)
uploadFile(file, backtopage)
// 將上傳文件的方法掛載到vue的原型鏈上面
// Vue.prototype.uploadFile = uploadFile

var requestCallback = function (err, data) {
console.log(err || data);
if (err && err.error) {
console.log(key)
// wx.showModal({ title: '返回錯誤', content: '請求失敗:' + err.error.Message + ';狀態碼:' + err.statusCode, showCancel: false });
} else if (err) {
console.log(key)
// wx.showModal({ title: '請求出錯', content: '請求出錯:' + err + ';狀態碼:' + err.statusCode, showCancel: false });
} else {
console.log(key)
backtopage(key)
// wx.showToast({ title: '上傳成功', icon: 'success', duration: 3000 });
}
};

function uploadFile (file, backtopage) {
console.log('nnnnnnnnnnnnnnnnnnn')
console.log(file)
// 得到md5碼
getFileMD5(file, md5 => {
console.log(file)
// 存儲文件的md5碼
file.md5 = md5
console.log(file.md5)
let subfix = file.name.substr(file.name.lastIndexOf('.'))
key = file.md5 + subfix
console.log(key)
cos.headObject({
Bucket: cosConfig.Bucket, /* 必須 */
Region: cosConfig.Region, /* 必須 */
Key: key, /* 必須 */
}, function (err, data) {
if (err != null) {
console.log('wrong')
console.log(err)
cos.putObject({
Bucket: cosConfig.Bucket,
Region: cosConfig.Region,
Key: key,
Body: file,
onProgress: function (info) {
console.log(JSON.stringify(info));
}
}, requestCallback)
} else if (data != null) {
backtopage(key)
}
});
})
}

// 獲得文件md5
function getFileMD5(file, callback) {
//聲明必要的變量
var fileReader = new FileReader(),

//文件每塊分割2M,計算分割詳情
chunkSize = 2097152,
chunks = Math.ceil(file.size / chunkSize),
currentChunk = 0,

//創建md5對象(基於SparkMD5)
spark = new SparkMD5()

//每塊文件讀取完畢之后的處理
fileReader.onload = function(e) {
//每塊交由sparkMD5進行計算
spark.appendBinary(e.target.result)
currentChunk++

//如果文件處理完成計算MD5,如果還有分片繼續處理
if (currentChunk < chunks) {
loadNext()
} else {
callback(spark.end())
}
}

//處理單片文件的上傳
function loadNext() {
var start = currentChunk * chunkSize,
end = start + chunkSize >= file.size ? file.size : start + chunkSize

fileReader.readAsBinaryString(file.slice(start, end))
}

loadNext()

}

}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM