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.
-
Use FormDataaarosil– aarosil2014-11-08 20:22:16 +00:00Commented Nov 8, 2014 at 20:22
-
So, I have to create FormData object and then insert data in it and send the FormData object to my API?Oleh Kuchuk– Oleh Kuchuk2014-11-11 11:29:13 +00:00Commented Nov 11, 2014 at 11:29
-
Exactly, I can post a more detail answer with sample code if you'd like.aarosil– aarosil2014-11-11 21:50:46 +00:00Commented Nov 11, 2014 at 21:50
-
@aarosil Please, post it , if you canOleh Kuchuk– Oleh Kuchuk2014-11-12 14:30:42 +00:00Commented Nov 12, 2014 at 14:30
2 Answers
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:
2 Comments
You can upload file using ngFileUpload or angularFileUpload directives.
In case of angularFileUpload, you use .upload in controller and in case of ngFileUpload, you use .http
Also, you can also use application/x-www-form-urlencoded content type instead of multipart provided your file is not huge. In case of application/x-www-form-urlencoded, you can just receive the value in rest webservice as normal InputStream thereby requiring no need of marshalling of multipart data.
You may refer the below for the possible ways to upload file using angular js and rest web service:
http://technoguider.com/2015/08/file-upload-using-angular-js-and-rest-web-service/