簡體   English   中英

如何使用Angular將JSON和文件發布到Web服務?

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

如何使用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!";
  }
}

我使用了角度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'}});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM