Ask Your Question

juminet's profile - activity

2017-07-31 19:25:27 -0600 asked a question Swift: unable to post files using the form post middleware with FormData (error 401)


We want to be able to upload files to a openstack container using the (form post middleware) but with a form that is dynamically generated with JS code. The idea is to dynamically prepare a (FormData) object and to post it using XmlHttprequest.

Here's our approach, in JS:

  • we listen to the input field where the user is dropping a file
  • when a file is dropped into the field, we:
    • request values for the signature and expires parameters + a correct url using a temporay url generator (which is working in a html form). These values are stored in a json object called data.
    • build a FormData object and append the requested values + the file that is dropped

var formData = new FormData();
formData.append("redirect", data.redirect);
formData.append("max_file_size", data.max_file_size);
formData.append("max_file_count", data.max_file_count);
formData.append("expires", data.expires);
formData.append("signature", data.signature);
formData.append("file", file_object);

  • send this FormData object using a xmlhttprequest as follows:

    var request = new XMLHttpRequest();"POST", url, true);


It results in a 401 error, with a "No 'Access-Control-Allow-Origin' header is present on the requested resource". However, it is working by using a html form (as explained in this (page)) when clicking on the submit button. We made many tests, such as adding a form to the DOM with empty parameters, create a FormData from this form, and then add the values. Using the html form (which is working), we tested our xmlhttprequest function and our formData object, with many configurations, and it's working well. However, when building the form, we always have the same error (or sometimes a 400 Bad request when we put "trash" into formData.)

So, how to post files using a FormData object and XmlHttpRequest?

2017-07-31 04:57:01 -0600 received badge  Supporter (source)