Vue implementation paste screenshots upload pictures
At the beginning of this demand, I can be stumped, in a variety of online search, most are the use of rich text paste function, but rich text mostly have toolbar, want to lazy I gave up 😁. The code is as follows (simplified)!
html
<div class="box">
<div id="preview" v-on:paste="handlePaste"</span> </div> <el-button V-on :click="uploadPlans"</el-button> </div>Copy the code
js
// Listen for the paste operation
handlePaste(event) {
const items = (event.clipboardData || window.clipboardData).items;
let file = null;
if(! items || items.length ===0) {
this.$message.error("Current browser does not support local");
return;
}
// Search for clipboard items
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image")! = =- 1) {
file = items[i].getAsFile();
break; }}if(! file) {this.$message.error("Pasting content is not a picture");
return;
}
// File is the image object in our clipboard
// If you need a preview, you can execute the following code
const reader = new FileReader();
reader.onload = event => {
preview.innerHTML = `<img src="${event.target.result}"> `; }; reader.readAsDataURL(file);this.file = file;
},
// The file was successfully uploaded
uploadPlans() {
let file = this.file;
if(! file) {this.$message.error("Please paste the picture and upload it");
return;
}
this.loading = true;
let form = new FormData();
form.append("file", file);
form.append("type".this.type);
//uploadCertificate is a wrapped AXIos request that passes its own parameters as required
uploadCertificate(form)
.then(data => {
if (data.data && data.data.success) {
this.certificate_pic = data.data.data.source;
this.$message.success(this.name + "Upload successful!");
} else {
this.$message.error(this.name + "Upload failed!"); }}).catch(() = > {}); },Copy the code
This is just the most basic function implementation code, you can add requirements as appropriate. The result is as follows. Only screenshots can be uploaded, such as qq, wechat, Dingding and other apps can be directly pasted.