1

Can Backbone send data as multipart/form-data? I believe it defaults to application/json. I looked through the documentation and if I do Backbone.emulateJSON = true it'll send as application/x-www-form-urlencoded but that doesn't help.

I'm working on a legacy project and I'm trying to add file-upload functionality to it. To do that though I'm told the server needs to be changed to accept multiform data rather than application/json data.

user2483724
  • 2,089
  • 5
  • 27
  • 43

3 Answers3

1

When you fetch, save, etc. you can optionally provide an options argument. Any options in it that aren't Backbone-specific ones (eg. silent: true) will be passed along to sync, which well then pass them along to $.ajax.

So, in short, you can do anything you could normally do with $.ajax by just passing the appropriate options when you make your Backbone AJAX method call.

machineghost
  • 33,529
  • 30
  • 159
  • 234
1

You can send data as mutipart by appending data to FormData() object ,and making your form enctype="multipart/form-data".You can also send File object through this.

<form class="form form-inline" id="quotation_form" method="post" data-remote="true" enctype="multipart/form-data" >

 </form>


     var data = new FormData();
     data.append("description", description);


      quotationAttachmentModel.save(null, {
             processData: false,
             url: requestURL,
             data: data,
             cache: false,
             iframe: true,
             emulateJSON: true,
             contentType: false,

      success: function(model, resp) {
        console.log("success");
      },
      error: function(data, jqXHR, errorThrown) {
        console.log("failed");
      }
    });
0

I suggest that you do the file upload using an explicit transport, e.g. jQuery.ajax or similar, as the uploads don't really resemble Backbone.Models anyway. Also, you might want to use a library such as jquery-fileupload and subscribe to the events it emits. Also check this for ideas.

Roman
  • 13,100
  • 2
  • 47
  • 63