How to install POST JSON and file in web service using Angular?

How to send a POST request using AngularJS? Part of the JSON is required, but the file is missing. I tried this based on other blog posts, but it does not work. I get a Bad request 400 error.

200 points will be added to the correct answer.

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 } }); 
+6
source share
2 answers

I checked 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 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 the network tab of the Chrome console):

 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-- 

The answer is 200 OK, and the console displays the expected: {"description":"Test","status":"REJECTED"}

+15
source

You can publish JSON content directly in POST data.

 $http.post(URI, JSON.stringify(test)); 

Depending on the API specification, you may need to add a content type.

 $http.post(URI, JSON.stringify(test), {headers: {'Content-Type': 'application/json'}}); 
-3
source

Source: https://habr.com/ru/post/951602/


All Articles