【问题标题】:Match a curl request to NancyFx service from browser js从浏览器 js 将 curl 请求匹配到 NancyFx 服务
【发布时间】:2016-07-23 00:30:17
【问题描述】:

我有一个微服务(在 NancyFx 中),可以按预期运行以下 cURL 命令:

curl --verbose   --form file=@"C:\test\image.png"  http://localhost:8080/file/upload

该文件按预期显示在 Nancy 内部:

context.Request.Files[0]  //The file bytes are here, yeah!!

现在我必须让我的网络客户端以相同的方式将选定的文件发送到相同的服务。

TLDR;如果您愿意,可以跳过下面我的失败示例

我尝试了以下几个版本,但均未成功:

    var uploadForm = new FormData();  
    // Add the file to the request.
    uploadForm.append("file", file, name);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://localhost:8080/file/upload', true);
    xhr.onload = function() {
        if (xhr.status === 200)
            alert('File ' + name + 'Upload successfully!!!');
        else errorFn("Upload Failure on file " + name);
    };

    //Send the data
    xhr.send(uploadForm);

以及以下几个版本,也没有成功:

    var postConfig = {
        url: 'http://localhost:8080/file/upload',
        data: uploadForm,
        processData: false, //tries without this as well
        type: "POST",
        dataType: "application/x-www-form-urlencoded; charset=UTF-8",
        cache: false,
        success: successFn,
        error: errorFn
    }
    $.ajax(postConfig);

我已经尝试过上述方法

  1. file = 直接引用 $('MyFileSelectorControl').files[0]
  2. 使用以下代码设置文件:

    var reader = new FileReader();
    reader.onload = function (result) {
        var fileContent = new Uint8Array(result.target.result);
        var encContent = new SP.Base64EncodedByteArray();
        for (var b = 0; b < fileContent.length; b++) {
            encContent.append(fileContent[b]);
        }
        <Set file = encContent and send AJAZ as above>
    };
    reader.readAsArrayBuffer(fileInput);
    
    1. 将 file = 设置为上面的 fileContent(IOW,在通过阅读器后,但未编码。)

如何从 javascript(jQuery 或标准)提交此文件,以便它像在 cURL 中一样工作?

【问题讨论】:

    标签: javascript curl file-upload nancy asyncfileupload


    【解决方案1】:

    这是最终有效的代码。 (诚​​然,我以为我已经尝试过这个并在我的问题中这么说)

    var file = $('MyFileSelectorControl').files[0];
    var uploadForm = new FormData();  
    // Add the file to the request.
    uploadForm.append("file", file, name);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://localhost:8080/file/upload', true);
    xhr.onload = function() {
        if (xhr.status === 200)
            alert('File ' + name + 'Upload successfully!!!');
        else errorFn("Upload Failure on file " + name);
    };
    
    //Send the data
    xhr.send(uploadForm);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2020-06-30
      • 1970-01-01
      • 2012-05-10
      • 2015-07-12
      • 2013-08-13
      • 2016-01-11
      • 2013-03-19
      相关资源
      最近更新 更多