最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to POST JSON and a file to web service with Angular? - Stack Overflow

programmeradmin6浏览0评论

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.

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
  }
});

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.

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
  }
});
Share Improve this question edited May 19, 2023 at 23:31 ggorlen 57.1k8 gold badges110 silver badges150 bronze badges asked Aug 13, 2013 at 7:31 LuckyLukeLuckyLuke 49.1k87 gold badges279 silver badges446 bronze badges 6
  • Just to make sure, you want to send in a single request both an encoded file and JSON content? Can you clarify on the flow you want to get? – Benjamin Gruenbaum Commented Aug 13, 2013 at 10:39
  • @Benjamin Gruenbaum: Yes that is correct, all in one request. I have created a Java Spring backend that takes a JSON part which is required, and a file part that is optional. I have a form where the user enter data, the model is then converted to Json by the angular.toJson(..) and then I want to post that. The user can also choose to upload a file in the same form. – LuckyLuke Commented Aug 13, 2013 at 10:43
  • Hmmm, this can be a little work or a lot of what, what browsers do you have to support? – Benjamin Gruenbaum Commented Aug 14, 2013 at 4:53
  • I will not care about ancient browswers. People using my web page should have a html5 browser. – LuckyLuke Commented Aug 14, 2013 at 9:23
  • FormData is definitely the way to go then, you seem halfway through, you are appending the JSON data to the form but not the file, you should call fd.append on your file (or create a Blob from it) and send it. (See this tutorial on FormData, if you have any feedback on it I'd like to hear too :)). Once you set it up you still need to support Multipart in Spring. This requires goo.gl/iYguqz . I'd also use normal XHR and not $http for this to be honest,newer versions of Angular probably fixed some of he old problems Angular had with FormData in AJAX though. – Benjamin Gruenbaum Commented Aug 14, 2013 at 12:52
 |  Show 1 more ment

2 Answers 2

Reset to default 17 +200

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 ment 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"}

You can post the JSON content directly in the POST data.

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

Depending on the API specification, you might have to add the content-type.

$http.post(URI, JSON.stringify(test), {headers: {'Content-Type': 'application/json'}});
发布评论

评论列表(0)

  1. 暂无评论