繁体   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