upload file to RESTful service in angularjs

16,792

Something like this should work well to send as multipart/form-data request to backend API:

var file = ... // get from file input;
var backendUrl = ...
var fd = new FormData();

fd.append('myFile', file, 'filename.ext');

$http.post(backendUrl, fd, {
    // this cancels AngularJS normal serialization of request
    transformRequest: angular.identity,
    // this lets browser set `Content-Type: multipart/form-data` 
    // header and proper data boundary
    headers: {'Content-Type': undefined}
})

.success(function(){
    //file was uploaded
})

.error(function(){
    //something went wrong 
});

See here for reference:

FormData API Doc

Using FormData Objects (MDN)

multipart-formdata file upload with AngularJS

Share:
16,792
Oleh Kuchuk
Author by

Oleh Kuchuk

Updated on June 24, 2022

Comments

  • Oleh Kuchuk
    Oleh Kuchuk almost 2 years

    i try to make angular CRUD app that is a bit like "dropbox". So, it must have file and folder hosting with sharing and access functionality. I'm stuck on a question how to upload image and video files? I used File API (FileReader, Blob) to make preview of files on the client side but i dont have idea how to POST this type of data to server.

    • aarosil
      aarosil over 9 years
      Use FormData
    • Oleh Kuchuk
      Oleh Kuchuk over 9 years
      So, I have to create FormData object and then insert data in it and send the FormData object to my API?
    • aarosil
      aarosil over 9 years
      Exactly, I can post a more detail answer with sample code if you'd like.
    • Oleh Kuchuk
      Oleh Kuchuk over 9 years
      @aarosil Please, post it , if you can
  • Oleh Kuchuk
    Oleh Kuchuk over 9 years
    It's very helpful. Thank you for your help.
  • FloydThreepwood
    FloydThreepwood about 8 years
    the by far simplest solution the interwebs provided, thanks
  • Nemus
    Nemus over 7 years
    How do you fill the "file" varialble? I mena, how to bind it to the input control?