Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST JSON and a file to web service with Angular?

How do I send a POST request with AngularJS? The JSON part is required but the file is not. I have tried this based on other blog posts but it does not work. I get a Bad request 400 error.

200 points to the correct answer will be added

var test = {
  description:"Test",
  status: "REJECTED"
};

var fd = new FormData();
fd.append('data', angular.toJson(test));

return $http.post('/servers', fd, {
  transformRequest: angular.identity,
  headers: {
    'Content-Type': undefined
  }
});
like image 503
LuckyLuke Avatar asked Aug 13 '13 07:08

LuckyLuke


1 Answers

I've tested your code with a simple Spring backend and it works fine:

@Controller
public class FileController {

  @ResponseBody
  @RequestMapping(value = "/data/fileupload", method = RequestMethod.POST)
  public String postFile(@RequestParam(value="file", required=false) MultipartFile file,
                       @RequestParam(value="data") Object data) throws Exception {
    System.out.println("data = " + data);

    return "OK!";
  }
}

I've used your client side code with angular v1.1.5:

var test = {
  description:"Test",
  status: "REJECTED"
};

var fd = new FormData();
fd.append('data', angular.toJson(test));

//remove comment to append a file to the request
//var oBlob = new Blob(['test'], { type: "text/plain"});
//fd.append("file", oBlob,'test.txt');

return $http.post('/data/fileupload', fd, {
  transformRequest: angular.identity,
  headers: {
    'Content-Type': undefined
  }
});

The request looks like this (copied from Chrome console network tab):

Request URL:http://localhost:8080/data/fileupload
Request Method:POST
Status Code:200 OK

Request Headers
POST /data/fileupload HTTP/1.1
Host: localhost:8080
...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryEGiRWBFzWY6xwelb
Referer: http://localhost:8080/
...
Request Payload
------WebKitFormBoundaryEGiRWBFzWY6xwelb
Content-Disposition: form-data; name="data"

{"description":"Test","status":"REJECTED"}
------WebKitFormBoundaryEGiRWBFzWY6xwelb--

Response 200 OK, and the console outputs the expected: {"description":"Test","status":"REJECTED"}

like image 57
joakimbl Avatar answered Oct 10 '22 14:10

joakimbl