0

I need to send a multipart form POST request from my web application running on Chrome. That works well with the following code:

<form method="post" action="http://localhost:999/some/path" target="iframeId" id="mainForm">
...
</form>
<iframe id="iframeId" name="iframeId" width="100%"></iframe>

I would like to create the multipart request payload manually instead, since the file to be submitted needs to be encrypted first.

var boundary = "---------------------------7da24f2e50046";
var body = '--' + boundary + '\r\n'
     + 'Content-Disposition: form-data; name="file";'
     + 'filename="temp.bin"\r\n'
     + 'Content-type: application/octet-stream\r\n\r\n'
     + body + '\r\n'
     + boundary + '--';

$.ajax({
    contentType: "multipart/form-data",
    data: body,
    type: "POST",
    url: "http://localhost:999/some/path",
    success: function (data, status) {
        alert('done');
    }
});

When I run this code I get the following error:

XMLHttpRequest cannot load localhost:999/some/path. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file://' is therefore not allowed access.

Why setting the target of the POST to an iFrame works, but an ajax won't? Is there a way to work around this, to be able to build my own multipart payload?

  • The only workaround is to send the data to your server and then to the other domain because of [SOP](https://en.wikipedia.org/wiki/Same-origin_policy). – Derek 朕會功夫 Jan 24 '14 at 07:36
  • I believe ajax does not that kind of request on another domain, have you checked out jsonp? http://stackoverflow.com/questions/5943630/basic-example-of-using-ajax-with-jsonp – Victor Soto Jan 24 '14 at 07:39

2 Answers2

0

To make a cross domain AJAX request the receiving domain must accept CORS requests, or you need to send in JSONP format. The latter is not really going to work for you as you're trying to send multi-part form data.

Your only option is to check if the receiving domain does indeed accept CORS. If not you will need to make this request on the server side.

This is all due to the Same Origin Policy which is a security policy that all modern browsers now implement.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Why setting the target of the POST to an iFrame works, but an ajax won't?

Because Ajax would let the JavaScript running in Alice's browser on the site (Mallory's site) that triggered the request access the response from Bob's site (which could leak private data to Mallory when only Alice and Bob should have access to it).

iframes have other mechanisms to prevent JS from accessing the data.

Is there a way to work around this, to be able to build my own multipart payload?

Several. The main ones are:

  • CORS
  • JSONP (not suitable for POST requests)
  • Having JS make the request to the same server and then relaying it using server side code
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335