如何使用Angular将JSON和文件POST到web服务

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

本文关键字:POST web 服务 文件 何使用 Angular JSON      更新时间:2023-09-26

如何使用AngularJS发送POST请求?JSON部分是必需的,但文件不是。我在其他博客文章的基础上尝试过这种方法,但它不起作用。我收到一个错误请求400错误

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

我用一个简单的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!";
  }
}

我已经使用了你的客户端代码与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
  }
});

请求如下(从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--

响应200 OK,控制台输出预期的:{"description":"Test","status":"REJECTED"}

您可以直接在post数据中发布JSON内容。

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

根据API规范,您可能需要添加内容类型。

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