问题描述
我正在创建一个 chrome 扩展程序,用于处理文件上传。我想要做的是下载一个图像,然后将其上传到并在下载后立即输入[type='file']。
到目前为止,我使用的是来自 https://stackoverflow.com/a/21422922/16064324 的代码。
// load the image
var img = new Image();
img.setAttribute('crossOrigin','anonymous');
img.src = result.products[pointer][3];
// loaded
img.onload = function() {
// convert the image into a data url
var dataUrl = getimageDataUrl(img);
var blob = dataUrlToBlob(dataUrl);
// FormData will encapsulate the form,and understands blobs
var formData = new FormData();
// "image_name.png" can be whatever you want; it's what the
// host will see as the filename for this image (the host server
// that receives the posted form). it doesn't have to match the
// original filename,and can be arbitrary or not provided at all.
formData.append("file",blob,"image_name.png");
var request = new XMLHttpRequest();
// upload
request.open("POST","https://www.facebook.com/marketplace/create/item");
request.send(formData);
};
// converts an image into a dataurl
function getimageDataUrl(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0);
// NOTE: this will throw a cross-origin security exception
// if not done in an extension and if the image is cross-origin
return canvas.toDataURL("image/png");
}
// converts a dataurl into a blob
function dataUrlToBlob(dataUrl) {
var binary = atob(dataUrl.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)],{type: 'image/png'});
}
图像被发送到服务器 Image sent to server。在这张图片中,您可以看到我想要的图片已发送到服务器,它是蓝色突出显示的那个。
这工作正常,但是我如何将完全相同的图像上传到页面 input[type='file'] section。即使图片发送到服务器,输入部分仍然显示有0张图片,我如何将上传的图片添加到此输入部分>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)