Uploading a File with Ajax POST, Multipart content and JSON payload

廉价感情. 提交于 2019-12-23 18:53:26

问题


There is a REST service, which enables me to upload a file. I have to construct a POST request with the following payload, for example:

Content-Type: multipart/form-data; boundary= ---1234567890
-----1234567890
Content-Disposition: form-data; name="parameters"
Content-Type: application/json

{
"parentID":"FB4CD874EF94CD2CC1B60B72T0000000000100000001"
}
-----1234567890
Content-Disposition: form-data; name="primaryFile"; filename="example.txt"
Content-Type: text/plain

<File Content>
-----1234567890--

Looks simple enough. The first part is a JSON object, that decribes the location on the server, where the file should be saved, the second part is the file itself. (Please note that I am n no position to modify the server.)

After lots of googling, I discovered that I can use FormData object to create this multipart request. Here is my code:

function checkInNewFile(folderId, file)
{
  var response;
  var fd = new FormData();

  var parent = new Blob(['{ "parentID": "' + folderId + '" }"'], { type: "application/json"});
  fd.append("parameters", parent, null);

  fd.append("primaryFile", file);

  var jqXHR =
    $.ajax(
      {
        type: "POST",
        url: someURL,
        async: false,

        data: fd,
        processData: false,
        contentType: false
      }
    );
  jqXHR.done( function (data) { response = data; });
  return response;
}

The generated request is almost the expected one ... the file content is correct, but I am unable to create exactly the first part. Actually the code above produce this first part:

-----1234567890
Content-Disposition: form-data; name="parameters"; filename=""
Content-Type: application/json

{
"parentID":"FB4CD874EF94CD2CC1B60B72T0000000000100000001"
}

As you see, there is an additional filename attribute in the request, and although the actual name is empty, my server does not like the request in this form.

Of course I tried to add a simple text value as the first part:

  var parent = '{ "parentID" : "' +  folderId + '" }';
  fd.append("parameters", parent);

but now the request looks like:

-----1234567890
Content-Disposition: form-data; name="parameters"

{ "parentID":"FB4CD874EF94CD2CC1B60B72T0000000000100000001" }

i.e. the Content-Type is missing, and it is not accepted by the server.

I was trying to add the data as an object, but it did not help at all, either the Content-type or the actual JSON representation, or both were missing.

Reading the FormData documentation, I did not find any other choice. And I do not know enough JavaScript to rewrite FormData from scratch.

Any idea?

来源:https://stackoverflow.com/questions/22539682/uploading-a-file-with-ajax-post-multipart-content-and-json-payload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!