簡體   English   中英

如何使用客戶端 javascript 創建內存文件並上傳到服務器?

[英]How to create an in memory file and upload to server using client side javascript?

我有一個用 JavaScript 編寫的測試套件,該測試套件在瀏覽器中運行,該瀏覽器在嵌入式系統上運行。 測試套件收集了大量數據,我想將其推送到服務器。 我可以使用一個簡單的 HttpRequest 后置方法,但這需要大量字符轉義才能發送內容。 使用 http-file-upload 將其作為文件上傳到服務器會簡單得多。

有沒有辦法使用客戶端 JavaScript 創建內存文件並使用 http-file-upload 將其推送到服務器?

由於嵌入式系統的瀏覽器是Ekioh,系統本身是最小的,flash、JavaApplet、SilverLight等技術都沒有。 只有純 HTML5 和 JavaScript 可用。

我認為發布帖子將是更好的方法。 處理轉義的數據比使用內存中的文件和使用客戶端JavaScript將文件推送到服務器要容易得多,更成熟。 此外,轉義數據是有原因的。 您要嘗試做的就是迎接許多安全漏洞。

嘗試做這樣的事情。 摘錄自將javascript輸出寫入服務器上的文件

var data = "...";// this is your data that you want to pass to the server (could be json)
//next you would initiate a XMLHTTPRequest as following (could be more advanced):
var url = "get_data.php";//your url to the server side file that will receive the data.
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);//check if the data was revived successfully.
    }
}
http.send(data);

這對我有用。 關鍵部分是創建文件和 blob。 我使用 Angular JS 來進行實際的 http 調用。 但是,一旦您在內存中有了一個文件,使用您的 http 客戶端發送數據應該不會太難。

注意:我對https://httpbin.org/post進行了 http 調用。 這與服務器接收/解析的內容相呼應,這在迭代以找出您的問題時很有用。

function multiPartPost(bodyObj) {
  const url = 'https://httpbin.org/post';

  const bodyJson = JSON.stringify(bodyObj);
  const blob = new Blob([bodyJson], {
    type: 'application/json;charset=UTF-8'
  });
  const fileName = 'jsonAttrs';
  const file = new File([blob], fileName, {type: "text/json;charset=utf-8"});
  const formData = new FormData();
  formData.append(fileName, file);

  return this.$http.post(url, formData, {
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
  });
}

暫無
暫無

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

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