如何使用 Angular 将 JSON 和文件发布到 Web 服务? [英] How to POST JSON and a file to web service with Angular?

查看:30
本文介绍了如何使用 Angular 将 JSON 和文件发布到 Web 服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

正确答案加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 后端测试了你的代码,它运行良好:

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!";
  }
}

我在 angular v1.1.5 中使用了你的客户端代码:

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 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 控制台网络选项卡复制):

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

Response 200 OK, and the console outputs the expected: {"description":"Test","status":"REJECTED"}

这篇关于如何使用 Angular 将 JSON 和文件发布到 Web 服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆