Question

I'm developing a Javascript app and I need to use the Mediafire REST API to upload a file. (See upload ducmentation here).

Following this MDN tutorial, and some research, I've written the code below, but it seems it's not working... Note that I don't need for the moment to control the progress and so on, I only want to do the most basic upload operation possible...

Also note that I could a different code, and even jQuery or other (free) libraries, so if you have a better code to upload a file I'd be really grateful...

var controller = this;
var file = $("#file").get(0).files[0];
//The file is correctly retrieved here...

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.mediafire.com/api/upload/upload.php?session_token=' + controller.sessionToken.token);
//(The session_token is valid)
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.setRequestHeader('x-filesize', file.size);

var reader = new FileReader();
reader.onload = function (evt) {
  var uInt8Array = new Uint8Array(evt.target.result);
  //It seems that here the ArrayBuffer is read correctly, 
  //and I converted it to a ArrayBufferView because Chrome suggested it...
  xhr.send(uInt8Array);
};
reader.readAsArrayBuffer(file);

I can't tell the concrete error, I only know that nothing is happens... but maybe looking at the code you can see some obvious error... The only thing I see is this in Chrome's console:

enter image description here

enter image description here

Note: I know the quality of this question is not the desired and it's TOO vague, but I tried to do my best taking into account that I'm completely new to ALL these technologies...

Was it helpful?

Solution

The presence of an OPTIONS request and the presence of specific headers in the OPTIONS request indicates that your POST request is a cross-domain request. The user agent, following the CORS spec, is first sending an OPTIONS request. This is also called a preflight request, and it is sent, in your case, due to the non-standard header you are including (x-filesize) and the fact that the Content-Type is not form-encoded, MPE, or text/plain. You can either deal with the OPTIONS request server-side, or make appropriate changes to your request so that a preflight is not required. Either way, you are going to have to deal with CORS requests server-side since you are apparently making a cross-domain request. You can read more about CORS in this excellent MDN article.

P.S. Why are you using FileReader here? Just send the File object via XHR, or, better yet, append the File to a FormData object and send that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top