Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  198] [ 6]  / answers: 1 / hits: 138657  / 11 Years ago, fri, may 10, 2013, 12:00:00

I have the below request in python



import requests, json, io

cookie = {}
payload = {Name:abc}
url = /test
file = out/test.json

fi = {'file': ('file', open(file) )}
r = requests.post(http://192.168.1.1:8080 + url, data=payload, files=fi, cookies=cookie)
print(r.text)


which send a file, and form fields to the backend. How can I do the same (sending file + form fields) with Angular $http. Currently, I do like this, but not sure how to send the file too.



var payload = {Name:abc};
$http.post('/test', payload)
.success(function (res) {
//success
});

More From » angularjs

 Answers
1

I recently wrote a directive that supports native multiple file uploads. The solution I've created relies on a service to fill the gap you've identified with the $http service. I've also included a directive, which provides an easy API for your angular module to use to post the files and data.



Example usage:



<lvl-file-upload
auto-upload='false'
choose-file-button-text='Choose files'
upload-file-button-text='Upload files'
upload-url='http://localhost:3000/files'
max-files='10'
max-file-size-mb='5'
get-additional-data='getData(files)'
on-done='done(files, data)'
on-progress='progress(percentDone)'
on-error='error(files, type, msg)'/>


You can find the code on github, and the documentation on my blog



It would be up to you to process the files in your web framework, but the solution I've created provides the angular interface to getting the data to your server. The angular code you need to write is to respond to the upload events



angular
.module('app', ['lvl.directives.fileupload'])
.controller('ctl', ['$scope', function($scope) {
$scope.done = function(files,data} { /*do something when the upload completes*/ };
$scope.progress = function(percentDone) { /*do something when progress is reported*/ };
$scope.error = function(file, type, msg) { /*do something if an error occurs*/ };
$scope.getAdditionalData = function() { /* return additional data to be posted to the server*/ };

});

[#78307] Thursday, May 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;