<template>
<div class="about">
<div class="box">
<div id="preview" class="upload-preview" v-on:paste="handlePaste">
</div>
<el-button v-on:click="uploadPlans" type="primary" style="margin-top:20px;">上传文件</el-button>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {};
},
methods: {
handlePaste(event) {
const items = (event.clipboardData || window.clipboardData).items;
let file = null;
if (!items || items.length === 0) {
alert("当前浏览器不支持本地");
return;
}
// 搜索剪切板items
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
file = items[i].getAsFile();
break;
}
}
if (!file) {
alert("粘贴内容非图片");
return;
}
// 此时file就是我们的剪切板中的图片对象
// 如果需要预览,可以执行下面代码
const reader = new FileReader();
reader.onload = (event) => {
preview.innerHTML = `<img src="${event.target.result}">`;
};
reader.readAsDataURL(file);
this.file = file;
},
//上传文件成功后回调
uploadPlans() {
let file = this.file;
if (!file) {
alert("请粘贴图片后上传");
return;
}
this.loading = true;
//FormData转为二进制 利用append确定参数 可根据自己需要确认参数列表
let form = new FormData();
form.append("api", "file@upload");
form.append("filename", file);
//uploadCertificate是封装的axios请求,自己根据需求传参
this.uploadCertificate(form)
.then((data) => {
console.log(data.code);
if (data.code == 200) {
alert("上传成功!");
} else {
alert("上传失败!");
}
})
.catch(() => {});
},
uploadCertificate(formData) {
//formData格式可以转为二进制
return new Promise((resolve, reject) => {
axios({
method: "POST",
url: "自己的url路径",
headers: {
"Content-Type": "multipart/form-data",
token: "设置token",
},
data: formData,
})
.then((data) => {
console.log(data);
if ((data.data.code = 200)) {
if (data.data) {
resolve({
default:
"https://staticonline.superhub.com.cn/" +
data.data.data.img,
code: 200,
});
} else {
reject(data.data.code);
}
}
})
.catch((e) => {
console.log(e);
reject();
});
});
},
},
};
</script>
<style lang="less" scoped>
.upload-preview {
min-height: 150px;
width: 400px;
margin: auto;
margin-top: 20px;
image{
width: 500px;
height: 500px;
}
}
.upload-preview:empty::before {
border: 1px solid #ddd;
content: "预览区";
display: block;
text-align: center;
font-size: 40px;
line-height: 150px;
opacity: 0.6;
}
</style>
标签:vue,return,剪贴,上传,code,file,items,data
From: https://www.cnblogs.com/wx-self-it/p/16824592.html