gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:08:13 26 4
gpt4 key购买 nike

如何使用 AngularJS 发送 POST 请求? JSON 部分是必需的,但文件不是。我已经根据其他博客文章尝试过此操作,但它不起作用。我收到一个错误请求 400 错误

答对加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
}
});

最佳答案

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

关于javascript - 如何使用 Angular 将 JSON 和文件发布到 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18203145/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com