上一篇文章写的是react的oss阿里云上传。这篇写vue的 ,没办法,PC用的react 框架。移动端是vue。。。
有问题请求留言。有关其他的一些引入的文件,我后续会补上,都是一些依赖!
####修改了一个问题,安卓微信页面打开提示:没有应用执行次操作!
####优化代码逻辑,可以直接服用随便修改
####删除无用的代码及默认值
还是老样子先看一下样式吧
上传后的样子
话不多说,父组件代码,引入upload组件
//引入oss组件代码
import UploadAli from "components/upload";
//使用组件 并传递事件和参数
<UploadAli :uploadAli="{userId,userName,groupId}" @uploadPhoto="onShowMainScene"></UploadAli>
然后就是该组件的代码
<template>
<div class="upload">
<button ref="chooseBtn" class="uploadBtn" id="uploadBtn">{{msg}}</button>
<button ref="uploadBtn" :class="[isOk ? 'uploadTitle' :'uploadTitle_ok']">{{ uploadTitle }}</button>
<span class="uploadText">用以制作考试证件,像素为626*413,格式为jpg或png,大小40KB-120KB</span>
</div>
</template>
<script>
import "./lib/crypto.js";
import "./lib//hmac.js";
import "./lib/sha1.js";
import plupload from "plupload";
import { Base64 } from "js-base64";
export default {
name: "UploadAli",
props: {
uploadData: {
type: Object,
default: () => ({
userId: 1,
userName: "",
groupId: 1
})
}
},
data() {
return {
isOk: false,
msg: "选择参赛者2寸证件照",
fileList: [],
uploadTitle: "上传",
policyBase64: "",
bytes: "",
signature: "",
uploadAli: {
dirname: "zhegedifangzijixie/",
finished: true,
files: {
limit: 1,
size: 120 * 1024,
progress: false,
extensions: [".jpg", ".png", ".jpeg"],
repetition: true,
img: {
size: [626, 413],
limit: [">=", ">="]
}
}
},
config: {
ossUrl: "zhegedifangzijixie",
host: "zhegedifangzijixie",
accessid: "zhegedifangzijixie",
accesskey: "zhegedifangzijixie",
policyText: {
expiration: "2020-01-01T12:00:00.000Z",
conditions: [["content-length-range", 0, 1048576000]]
}
},
uploaderObj: {
}
};
},
mounted() {
this.init();
},
methods: {
init() {
this.policyBase64 = Base64.encode(JSON.stringify(this.config.policyText));
this.bytes = Crypto.HMAC(
Crypto.SHA1,
this.policyBase64,
this.config.accesskey,
{
asBytes: true
}
);
this.signature = Crypto.util.bytesToBase64(this.bytes);
this.pluploadInit();
},
pluploadInit() {
this.uploadAli.files.img && this.addFileFilterImg();
this.uploaderObj = new plupload.Uploader({
url: this.config.ossUrl,
browse_button: this.$refs.chooseBtn,
multi_selection: false,
filters: {
// Do not use this method on the mobile side, because, because Android WeChat does not support。。。。
// mime_types: [{
// extensions: "jpg,png,gif,jpeg"
// }],
prevent_duplicates: this.uploadAli.files.repetition,
max_file_size: this.uploadAli.files.size,
imgSize: this.uploadAli.files.img.size
},
runtimes: "html5,flash,silverlight,html4",
silverlightXapUrl: "plupload/js/Moxie.xap",
init: {
PostInit: this.PostInit,
FileFiltered: this.FileFiltered,
FilesAdded: this.FilesAdded,
BeforeUpload: this.BeforeUpload,
UploadComplete: this.UploadComplete,
UploadProgress: this.UploadProgress,
FileUploaded: this.FileUploaded,
StateChanged: this.StateChanged,
Error: this.Error
}
});
this.uploaderObj.init();
},
StateChanged(uploader) {
},
PostInit(uploader) {
this.$refs.uploadBtn.onclick = () => {
uploader.start();
};
},
FileFiltered(uploader, file) {
// Radio directly go false
// eslint-disable-next-line no-constant-condition
if (false) {
if (this.uploadAli.files.limit && uploader.files.length > this.uploadAli.files.limit) {
uploader.removeFile(file);
} else {
this.uploadAli.finished = false;
}
} else {
if (uploader.files.length > 1) {
this.listKillFile(uploader.files[0]);
this.removeFile(uploader.files[0]);
}
this.msg = `${file.name}(${plupload.formatSize(file.size)})`;
this.uploadAli.finished = false;
}
},
// add files
FilesAdded(uploader, files) {
this.isOk = false;
this.uploadTitle = "上传";
plupload.each(files, (file) => {});
},
// Before uploading a single file
BeforeUpload(uploader, file) {
const fileName = `${+this.uploadData.userId}_${this.uploadData.groupId}_${this.uploadData.userName}${this.getSuffix(file.name)}`;
this.$emit(
"uploadPhoto",
`${this.config.host}/${this.uploadAli.dirname}${fileName}`
);
this.fileList.push({
fileName,
id: file.id,
name: file.name
});
const newMultipartParams = {
Filename: "photoExport/",
key: `${this.uploadAli.dirname}${fileName}`,
policy: this.policyBase64,
OSSAccessKeyId: this.config.accessid,
success_action_status: "200",
signature: this.signature,
multi_selection: false
};
uploader.setOption({
url: this.config.host,
multipart_params: newMultipartParams
});
},
UploadComplete(uploader, files) {
this.uploadAli.finished = true;
},
// Single file upload progress
UploadProgress(uploader, file) {
this.fileState = `${file.percent}%`;
this.filePercent = file.percent;
},
// After a single file is uploaded
FileUploaded(uploader, file, info) {
if (info.status === 200) {
this.isOk = true;
this.uploadTitle = "已上传";
this.showWaring(`照片上传成功`);
}
},
Error(uploader, err) {
switch (err.code) {
case -200:
this.showWaring(`网络发生错误`);
break;
case -300:
this.showWaring(`磁盘读写错误`);
break;
case -600:
this.showWaring(`上传文件体积不能超过${this.computeSize(this.uploadAli.files.size)}`);
break;
case -601:
this.showWaring(`选择的文件类型不符合要求`);
break;
case -602:
this.showWaring(`选取文件重复`);
break;
default:
this.showWaring(`${err}`);
}
},
computeSize(size) {
let sizeStr = ``;
if (size < 1024) {
sizeStr = `${size}B`;
} else if (size >= 1024 && size < 1024 * 1024) {
sizeStr = `${(size / 1024).toFixed(1)}KB`;
} else if (size >= 1024 * 1024 && size < 1024 * 1024 * 1024) {
sizeStr = `${(size / 1024 / 1024).toFixed(1)}MB`;
} else if (
size >= 1024 * 1024 * 1024 &&
size < 1024 * 1024 * 1024 * 1024
) {
sizeStr = `${(size / 1024 / 1024 / 1024).toFixed(1)}GB`;
}
return sizeStr;
},
removeFile(file) {
if (file.status === 2) {
this.uploaderObj.stop();
this.showWaring(`上传已终止`);
}
this.uploaderObj.removeFile(file);
this.uploadAli.finished = true;
this.uploaderObj.files.some((item) => {
if ([1, 2].includes(item.status)) {
this.uploadAli.finished = false;
return true;
}
});
this.listKillFile(file);
},
listKillFile(file) {
this.fileList.some((item, i, arr) => {
if (item.id === file.id) {
arr.splice(i, 1);
return true;
}
});
},
// Add a custom filter type
addFileFilterImg() {
plupload.addFileFilter("imgSize", (imgSize, file, cb) => {
if (!file.type.includes("image")) {
this.showWaring(`请上传图片文件!`);
} else if (!this.checkPhoto(this.getSuffix(file.name))) {
this.showWaring(`请上传JPG、PNG格式的图片!`);
} else if (file.type.includes("image") && !file.type.includes("gif")) {
let img = new plupload.moxie.image.Image();
img.onload = () => {
let flag = true;
const msg = [];
const imgMsg = [
this.contrast(img.width, 0),
this.contrast(img.height, 1)
];
imgMsg.forEach((item) => {
if (!item.flag) {
flag = false;
}
if (item.rule) {
msg.push(`图片${item.type}需${item.rule}${item.imgSize}像素`);
}
});
if (msg.length > 0) {
console.log(msg);
this.showWaring(`${msg.join(",")}`);
}
img.destroy();
img = null;
cb(flag);
};
img.onerror = () => {
console.log("imgOnError", img);
img.destroy();
img = null;
cb(false);
};
img.load(file.getSource());
} else {
cb(true);
}
});
},
contrast(size, num) {
let flag = false;
let rule = "";
const imgSize = this.uploadAli.files.img.size[num];
let type = "宽";
if (num === 1) {
type = "高";
}
switch (this.uploadAli.files.img.limit[num]) {
case "=":
if (size === imgSize) {
flag = true;
} else {
rule = "等于";
}
break;
case "!=":
if (size !== imgSize) {
flag = true;
} else {
rule = "不等于";
}
break;
case ">":
if (size > imgSize) {
flag = true;
} else {
rule = "大于";
}
break;
case "<":
if (size < imgSize) {
flag = true;
} else {
rule = "小于";
}
break;
case ">=":
if (size >= imgSize) {
flag = true;
} else {
rule = "大于等于";
}
break;
case "<=":
if (size <= imgSize) {
flag = true;
} else {
rule = "小于等于";
}
break;
default:
if (size === imgSize) {
flag = true;
} else {
rule = "等于";
}
}
return {
flag,
rule,
type,
imgSize
};
},
// Verify image format
checkPhoto(ext) {
return this.uploadAli.files.extensions.indexOf(ext.toLowerCase()) !== -1;
},
// Get extension
getSuffix(fileName) {
const pos = fileName.lastIndexOf(".");
let suffix = "";
if (pos !== -1) {
suffix = fileName.substring(pos);
}
return suffix;
},
showWaring(mes) {
this.$modal.alert({
title: "",
content: mes,
btnContent: "确定"
});
}
// showFileMsg(file) {
// const name = `${this.config.host}/${this.uploadAli.dirname}${file.name}`;
// const size = this.computeSize(file.size);
// let status = ``;
// if (file.status === 5) {
// status = `(完成)`;
// } else if (file.status === 4) {
// status = `(失败)`;
// } else if (file.percent) {
// status = `(${file.percent}%)`;
// }
// return `文件:${name} - 大小:${size}${status}`;
// },
}
};
</script>
<style lang="less" scoped>
@img-url: "zhegedifangzijixie";
.upload {
display: block;
position: relative;
overflow: hidden;
width: 100%;
height: 200px;
margin-bottom: 22px;
margin-left: 0;
padding: 0;
.uploadBtn {
width: 440px;
height: 100px;
background: rgba(255, 255, 255, 1);
border-radius: 10px;
border: 3px solid rgba(255, 141, 26, 1);
font-size: 30px;
font-family: PingFangSC-Regular;
font-weight: 400;
color: rgba(255, 141, 26, 1);
line-height: 42px;
overflow: hidden;
}
.uploadTitle {
margin-left: 20px;
width: 230px;
height: 100px;
background: rgba(179, 189, 194, 1);
border-radius: 10px;
font-size: 30px;
font-family: PingFangSC-Regular;
font-weight: 400;
color: rgba(255, 255, 255, 1);
line-height: 42px;
border: none;
}
.uploadTitle_ok {
margin-left: 20px;
width: 230px;
height: 100px;
background: rgba(255, 141, 26, 1);
border-radius: 10px;
border: 3px solid rgba(255, 141, 26, 1);
font-size: 30px;
font-family: PingFangSC-Regular;
font-weight: 400;
color: rgba(255, 255, 255, 1);
line-height: 42px;
}
.uploadText {
display: block;
width: 690px;
height: 66px;
margin-top: 24px;
font-size: 24px;
font-family: PingFangSC-Medium;
font-weight: 500;
color: rgba(179, 189, 194, 1);
padding-left: 10px;
// line-height: 40px;
}
.files {
display: none;
}
}
</style>
**好了这个就是完整代码! **上一篇文章写的是react的oss阿里云上传。这篇写vue的 ,没办法,PC用的react 框架。移动端是vue。。。
有问题请求留言。有关其他的一些引入的文件,我后续会补上,都是一些依赖!
####修改了一个问题,安卓微信页面打开提示:没有应用执行次操作!
####优化代码逻辑,可以直接服用随便修改
####删除无用的代码及默认值
还是老样子先看一下样式吧
上传后的样子
话不多说,父组件代码,引入upload组件
//引入oss组件代码
import UploadAli from "components/upload";
//使用组件 并传递事件和参数
<UploadAli :uploadAli="{userId,userName,groupId}" @uploadPhoto="onShowMainScene"></UploadAli>
然后就是该组件的代码
<template>
<div class="upload">
<button ref="chooseBtn" class="uploadBtn" id="uploadBtn">{{msg}}</button>
<button ref="uploadBtn" :class="[isOk ? 'uploadTitle' :'uploadTitle_ok']">{{ uploadTitle }}</button>
<span class="uploadText">用以制作考试证件,像素为626*413,格式为jpg或png,大小40KB-120KB</span>
</div>
</template>
<script>
import "./lib/crypto.js";
import "./lib//hmac.js";
import "./lib/sha1.js";
import plupload from "plupload";
import { Base64 } from "js-base64";
export default {
name: "UploadAli",
props: {
uploadData: {
type: Object,
default: () => ({
userId: 1,
userName: "",
groupId: 1
})
}
},
data() {
return {
isOk: false,
msg: "选择参赛者2寸证件照",
fileList: [],
uploadTitle: "上传",
policyBase64: "",
bytes: "",
signature: "",
uploadAli: {
dirname: "zhegedifangzijixie/",
finished: true,
files: {
limit: 1,
size: 120 * 1024,
progress: false,
extensions: [".jpg", ".png", ".jpeg"],
repetition: true,
img: {
size: [626, 413],
limit: [">=", ">="]
}
}
},
config: {
ossUrl: "zhegedifangzijixie",
host: "zhegedifangzijixie",
accessid: "zhegedifangzijixie",
accesskey: "zhegedifangzijixie",
policyText: {
expiration: "2020-01-01T12:00:00.000Z",
conditions: [["content-length-range", 0, 1048576000]]
}
},
uploaderObj: {
}
};
},
mounted() {
this.init();
},
methods: {
init() {
this.policyBase64 = Base64.encode(JSON.stringify(this.config.policyText));
this.bytes = Crypto.HMAC(
Crypto.SHA1,
this.policyBase64,
this.config.accesskey,
{
asBytes: true
}
);
this.signature = Crypto.util.bytesToBase64(this.bytes);
this.pluploadInit();
},
pluploadInit() {
this.uploadAli.files.img && this.addFileFilterImg();
this.uploaderObj = new plupload.Uploader({
url: this.config.ossUrl,
browse_button: this.$refs.chooseBtn,
multi_selection: false,
filters: {
// Do not use this method on the mobile side, because, because Android WeChat does not support。。。。
// mime_types: [{
// extensions: "jpg,png,gif,jpeg"
// }],
prevent_duplicates: this.uploadAli.files.repetition,
max_file_size: this.uploadAli.files.size,
imgSize: this.uploadAli.files.img.size
},
runtimes: "html5,flash,silverlight,html4",
silverlightXapUrl: "plupload/js/Moxie.xap",
init: {
PostInit: this.PostInit,
FileFiltered: this.FileFiltered,
FilesAdded: this.FilesAdded,
BeforeUpload: this.BeforeUpload,
UploadComplete: this.UploadComplete,
UploadProgress: this.UploadProgress,
FileUploaded: this.FileUploaded,
StateChanged: this.StateChanged,
Error: this.Error
}
});
this.uploaderObj.init();
},
StateChanged(uploader) {
},
PostInit(uploader) {
this.$refs.uploadBtn.onclick = () => {
uploader.start();
};
},
FileFiltered(uploader, file) {
// Radio directly go false
// eslint-disable-next-line no-constant-condition
if (false) {
if (this.uploadAli.files.limit && uploader.files.length > this.uploadAli.files.limit) {
uploader.removeFile(file);
} else {
this.uploadAli.finished = false;
}
} else {
if (uploader.files.length > 1) {
this.listKillFile(uploader.files[0]);
this.removeFile(uploader.files[0]);
}
this.msg = `${file.name}(${plupload.formatSize(file.size)})`;
this.uploadAli.finished = false;
}
},
// add files
FilesAdded(uploader, files) {
this.isOk = false;
this.uploadTitle = "上传";
plupload.each(files, (file) => {});
},
// Before uploading a single file
BeforeUpload(uploader, file) {
const fileName = `${+this.uploadData.userId}_${this.uploadData.groupId}_${this.uploadData.userName}${this.getSuffix(file.name)}`;
this.$emit(
"uploadPhoto",
`${this.config.host}/${this.uploadAli.dirname}${fileName}`
);
this.fileList.push({
fileName,
id: file.id,
name: file.name
});
const newMultipartParams = {
Filename: "photoExport/",
key: `${this.uploadAli.dirname}${fileName}`,
policy: this.policyBase64,
OSSAccessKeyId: this.config.accessid,
success_action_status: "200",
signature: this.signature,
multi_selection: false
};
uploader.setOption({
url: this.config.host,
multipart_params: newMultipartParams
});
},
UploadComplete(uploader, files) {
this.uploadAli.finished = true;
},
// Single file upload progress
UploadProgress(uploader, file) {
this.fileState = `${file.percent}%`;
this.filePercent = file.percent;
},
// After a single file is uploaded
FileUploaded(uploader, file, info) {
if (info.status === 200) {
this.isOk = true;
this.uploadTitle = "已上传";
this.showWaring(`照片上传成功`);
}
},
Error(uploader, err) {
switch (err.code) {
case -200:
this.showWaring(`网络发生错误`);
break;
case -300:
this.showWaring(`磁盘读写错误`);
break;
case -600:
this.showWaring(`上传文件体积不能超过${this.computeSize(this.uploadAli.files.size)}`);
break;
case -601:
this.showWaring(`选择的文件类型不符合要求`);
break;
case -602:
this.showWaring(`选取文件重复`);
break;
default:
this.showWaring(`${err}`);
}
},
computeSize(size) {
let sizeStr = ``;
if (size < 1024) {
sizeStr = `${size}B`;
} else if (size >= 1024 && size < 1024 * 1024) {
sizeStr = `${(size / 1024).toFixed(1)}KB`;
} else if (size >= 1024 * 1024 && size < 1024 * 1024 * 1024) {
sizeStr = `${(size / 1024 / 1024).toFixed(1)}MB`;
} else if (
size >= 1024 * 1024 * 1024 &&
size < 1024 * 1024 * 1024 * 1024
) {
sizeStr = `${(size / 1024 / 1024 / 1024).toFixed(1)}GB`;
}
return sizeStr;
},
removeFile(file) {
if (file.status === 2) {
this.uploaderObj.stop();
this.showWaring(`上传已终止`);
}
this.uploaderObj.removeFile(file);
this.uploadAli.finished = true;
this.uploaderObj.files.some((item) => {
if ([1, 2].includes(item.status)) {
this.uploadAli.finished = false;
return true;
}
});
this.listKillFile(file);
},
listKillFile(file) {
this.fileList.some((item, i, arr) => {
if (item.id === file.id) {
arr.splice(i, 1);
return true;
}
});
},
// Add a custom filter type
addFileFilterImg() {
plupload.addFileFilter("imgSize", (imgSize, file, cb) => {
if (!file.type.includes("image")) {
this.showWaring(`请上传图片文件!`);
} else if (!this.checkPhoto(this.getSuffix(file.name))) {
this.showWaring(`请上传JPG、PNG格式的图片!`);
} else if (file.type.includes("image") && !file.type.includes("gif")) {
let img = new plupload.moxie.image.Image();
img.onload = () => {
let flag = true;
const msg = [];
const imgMsg = [
this.contrast(img.width, 0),
this.contrast(img.height, 1)
];
imgMsg.forEach((item) => {
if (!item.flag) {
flag = false;
}
if (item.rule) {
msg.push(`图片${item.type}需${item.rule}${item.imgSize}像素`);
}
});
if (msg.length > 0) {
console.log(msg);
this.showWaring(`${msg.join(",")}`);
}
img.destroy();
img = null;
cb(flag);
};
img.onerror = () => {
console.log("imgOnError", img);
img.destroy();
img = null;
cb(false);
};
img.load(file.getSource());
} else {
cb(true);
}
});
},
contrast(size, num) {
let flag = false;
let rule = "";
const imgSize = this.uploadAli.files.img.size[num];
let type = "宽";
if (num === 1) {
type = "高";
}
switch (this.uploadAli.files.img.limit[num]) {
case "=":
if (size === imgSize) {
flag = true;
} else {
rule = "等于";
}
break;
case "!=":
if (size !== imgSize) {
flag = true;
} else {
rule = "不等于";
}
break;
case ">":
if (size > imgSize) {
flag = true;
} else {
rule = "大于";
}
break;
case "<":
if (size < imgSize) {
flag = true;
} else {
rule = "小于";
}
break;
case ">=":
if (size >= imgSize) {
flag = true;
} else {
rule = "大于等于";
}
break;
case "<=":
if (size <= imgSize) {
flag = true;
} else {
rule = "小于等于";
}
break;
default:
if (size === imgSize) {
flag = true;
} else {
rule = "等于";
}
}
return {
flag,
rule,
type,
imgSize
};
},
// Verify image format
checkPhoto(ext) {
return this.uploadAli.files.extensions.indexOf(ext.toLowerCase()) !== -1;
},
// Get extension
getSuffix(fileName) {
const pos = fileName.lastIndexOf(".");
let suffix = "";
if (pos !== -1) {
suffix = fileName.substring(pos);
}
return suffix;
},
showWaring(mes) {
this.$modal.alert({
title: "",
content: mes,
btnContent: "确定"
});
}
// showFileMsg(file) {
// const name = `${this.config.host}/${this.uploadAli.dirname}${file.name}`;
// const size = this.computeSize(file.size);
// let status = ``;
// if (file.status === 5) {
// status = `(完成)`;
// } else if (file.status === 4) {
// status = `(失败)`;
// } else if (file.percent) {
// status = `(${file.percent}%)`;
// }
// return `文件:${name} - 大小:${size}${status}`;
// },
}
};
</script>
<style lang="less" scoped>
@img-url: "zhegedifangzijixie";
.upload {
display: block;
position: relative;
overflow: hidden;
width: 100%;
height: 200px;
margin-bottom: 22px;
margin-left: 0;
padding: 0;
.uploadBtn {
width: 440px;
height: 100px;
background: rgba(255, 255, 255, 1);
border-radius: 10px;
border: 3px solid rgba(255, 141, 26, 1);
font-size: 30px;
font-family: PingFangSC-Regular;
font-weight: 400;
color: rgba(255, 141, 26, 1);
line-height: 42px;
overflow: hidden;
}
.uploadTitle {
margin-left: 20px;
width: 230px;
height: 100px;
background: rgba(179, 189, 194, 1);
border-radius: 10px;
font-size: 30px;
font-family: PingFangSC-Regular;
font-weight: 400;
color: rgba(255, 255, 255, 1);
line-height: 42px;
border: none;
}
.uploadTitle_ok {
margin-left: 20px;
width: 230px;
height: 100px;
background: rgba(255, 141, 26, 1);
border-radius: 10px;
border: 3px solid rgba(255, 141, 26, 1);
font-size: 30px;
font-family: PingFangSC-Regular;
font-weight: 400;
color: rgba(255, 255, 255, 1);
line-height: 42px;
}
.uploadText {
display: block;
width: 690px;
height: 66px;
margin-top: 24px;
font-size: 24px;
font-family: PingFangSC-Medium;
font-weight: 500;
color: rgba(179, 189, 194, 1);
padding-left: 10px;
// line-height: 40px;
}
.files {
display: none;
}
}
</style>
好了这个就是完整代码!