Swift: unable to post files using the form post middleware with FormData (error 401)

asked 2017-07-31 05:48:28 -0600

juminet gravatar image


We want to be able to upload files to a openstack container using the https://docs.openstack.org/swift/latest/api/form_post_middleware.html (form post middleware) but with a form that is dynamically generated with JS code. The idea is to dynamically prepare a https://developer.mozilla.org/en-US/docs/Web/API/FormData (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();

    request.open("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 https://docs.openstack.org/swift/latest/api/form_post_middleware.html (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?

edit retag flag offensive close merge delete