Rovak / InlineAttachment

Easily paste and upload files/images in plain textareas
http://git.razko.nl/InlineAttachment
MIT License
620 stars 77 forks source link

Issues when adding extra headers #51

Closed tanordheim closed 9 years ago

tanordheim commented 9 years ago

In issue #46 support for extraHeaders was added; I attempted to use this now by adding the following to my InlineAttachment configuration:

{
  extraHeaders: { "Accept": "application/json" }
}

Whenever InlineAttachment attempts to upload files now, I get this error:

Uncaught InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': the object's state must be OPENED.

I tried moving the block that sets the headers down until after the XMLHttpRequest has been opened, but this did strangely enough not seem to have any effect; the error still occured. I'm not familiar with this code, or really XMLHttpRequest in general, so I'm not quite sure what is going on here. I'd be happy to fix and submit a pull request, but some ideas about what might be going on here would be great.

Rovak commented 9 years ago

Moving the code below the xhr.open solves the error for me:

xhr.open('POST', settings.uploadUrl);

// Add any available extra headers
if (typeof settings.extraHeaders === "object") {
    for (var header in settings.extraHeaders) {
        if (settings.extraHeaders.hasOwnProperty(header)) {
            xhr.setRequestHeader(header, settings.extraHeaders[header]);
        }
    }
}

xhr.onload = function() {
  // If HTTP status is OK or Created
  if (xhr.status === 200 || xhr.status === 201) {
    me.onFileUploadResponse(xhr);
  } else {
    me.onFileUploadError(xhr);
  }
};
if (settings.beforeFileUpload(xhr) !== false) {
  xhr.send(formData);
}
return xhr;

Could you try it and check if it works for you as well? Tested in Chrome Version 40.0.2214.91 (64-bit) on Ubuntu

tamagokun commented 9 years ago

after providing extra headers, immediately after the image uploaded, the browser would redirect to the local path to the dropped image (default event it seems).

Moving the extra headers block below xhr.open as suggested above worked perfectly.

Rovak commented 9 years ago

@tamagokun thanks for the confirmation, i will make a fix soonish

Rovak commented 9 years ago

Fixed in #54