微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何下载然后上传文件到 Chrome 扩展的输入文件类型?

如何解决如何下载然后上传文件到 Chrome 扩展的输入文件类型?

我正在创建一个 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 举报,一经查实,本站将立刻删除。