jabalsad
jabalsad

Reputation: 2421

Submitting data instead of a file for an input form

I'm using jQuery to retrieve an image and post it to another form:

handler = function(data, status) {
    ...
    var fd;
    fd = new FormData;
    fd.append("file", data);
    jQuery.ajax({
      url: target_url,
      data: fd,
      processData: false,
      contentType: false,
      type: "POST",
      complete: function(xhr, status) {
        console.log(xhr.status);
        console.log(xhr.statusCode);
      }
    });
};
jQuery.get(imageUrl, null, handler);

The form looks something like this:

<form>
  <input type="file" name="file" />
  ...
</form>

Things aren't working as expected. I'm getting a 200 response from the server side, and it renders the forms with some of the values pre-populated.

I've also tried setting contentType: "multipart/form-data"

Any ideas why this is not working?

Upvotes: 2

Views: 548

Answers (1)

Musa
Musa

Reputation: 97672

You're sending a string which will not be recognized as a file. Try sending a blob

fd.append("file", new Blob([data], { "type" : "text/plain" }));

I'm pretty sure this will only work for text files, unless you set the responseType on the original request.

Upvotes: 2

Related Questions