background
Two days ago, I made a function. The general requirement is to paste the screenshot into the browser, and then call the background image recognition interface to extract the text in the picture. The overall process is as shown below:
Train of thought
Here’s the idea:
- Listen for the browser paste event
- DataTransferItemList, DataTransferItem, FileReader, URl.createObjecturl
- Interact with background FormData
implementation
On paper come zhongjue shallow, must know this to practice.
Okay, so without further ado, go straight to the code:
// Listen for the paste event
document.addEventListener('paste'.function (e) {
const dataTransferItemList = e.clipboardData.items;
// Filter non-image types
const items = [].slice.call(dataTransferItemList).filter(function (item) {
return item.type.indexOf('image')! = = -1;
});
if (items.length === 0) {
return;
}
const dataTransferItem = items[0];
const blob = dataTransferItem.getAsFile();
/ / get base64
const fileReader = new FileReader();
fileReader.addEventListener('load'.function (e) {
let base64 = e.target.result;
});
fileReader.readAsDataURL(blob);
// If base64 is too long, you can also generate local temporary links
let url = URL.createObjectURL(blob);
// Upload the image to the background
upload(blob);
});
/ / upload
function upload(file) {
// formData
const formData = new FormData();
formData.append('file', blob, 'filename');
// Send the request
const xhr = new XMLHttpRequest();
xhr.open('POST'.'backend/path'.true);
xhr.addEventListener('load'.function () {
if (xhr.status === 200) {
const res = xhr.responseText;
// todo
// ...}}); xhr.send(formData); }Copy the code