简体   繁体   English

如何使用Angular将JSON和文件发布到Web服务?

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

How do I send a POST request with AngularJS? 如何使用AngularJS发送POST请求? The JSON part is required but the file is not. JSON部分是必需的,但文件不是。 I have tried this based on other blog posts but it does not work. 我已根据其他博客文章尝试了这一点,但它不起作用。 I get a Bad request 400 error . 我收到错误请求400错误

200 points to the correct answer will be added 将添加200点正确答案

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

I've tested your code with a simple Spring backend and it works fine: 我用一个简单的Spring后端测试了你的代码,它工作正常:

@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: 我使用了角度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): 该请求如下所示(从Chrome控制台网络标签中复制):

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"} 响应200 OK,控制台输出预期的: {"description":"Test","status":"REJECTED"}

You can post the JSON content directly in the POST data. 您可以直接在POST数据中发布JSON内容。

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

Depending on the API specification, you might have to add the content-type. 根据API规范,您可能必须添加内容类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM