簡體   English   中英

是否可以用 Blob 替換文件輸入?

[英]Is it possible to replace a file input with a Blob?

我正在使用一個我無法訪問源代碼的在線應用程序,但我能夠通過 iframe 在其上注入 javascript,因為我可以在同一個域中創建頁面。

這個應用程序有一個提交文件上傳和文件輸入的表單,認為:

<form>
   <!-- lots and lots of inputs -->
   <input type="file" name="blah">
</form>

我想使用此表單為這個特定文件提交一個 javascript Blob,而不是來自磁盤的文件,同時不干擾表單的其余部分。 我該怎么做呢?

可以用 blob 替換文件輸入值。

為此,您必須像這樣構造 File 對象:

let file = new File([blob], "filename.ext",{type:"mime/type", lastModified:new Date().getTime()});

然后創建 DataTransfer 對象並將此文件添加到其中。

 let container = new DataTransfer();
 container.items.add(file);

這將填充 DataTransfer 的文件列表,該列表可以分配給文件輸入的文件屬性。

fileInputElement.files = container.files;

正如在fiddle中看到的那樣,它被正確分配。 此外,我測試了上傳(使用 enctype="multipart/form-data" 的表單輸入)並且文件被正確傳遞到服務器。

可以使用 XMLHttpRequest 和FormData的新屬性

感謝@musa 的評論;-)

考慮這個(未經測試的)示例:

function sendFile() {
  var content = "<hello>world</hello>"; // set here the content of your file
  var blob = new Blob([content], { type: "text/xml"}); // set the type of content (eg: image/jpeg)

  var formData = new FormData();
  formData.append('blah', blob);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) {
    alert ('successfully (or not) sent');
  };

  xhr.send(formData);
}

更多信息:

注意: IE9(及更少)不支持 FormData

這對於Blob也是一樣的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM