且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 AngularJS $http 发送 multipart/form-data

更新时间:2022-03-31 07:40:21

如何使用AngularJS $http发送FormData

FormData 接口提供了一种轻松构建一组表示表单字段及其值的键/值对,然后可以使用 XHR 发送 方法.如果编码类型设置为 multipart/form-data,它使用的格式与表单将使用的格式相同.

How to use AngularJS $http to send FormData

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XHR Send method. It uses the same format a form would use if the encoding type were set to multipart/form-data.

var formData = new FormData();

formData.append('type', type);
formData.append('description', description);
formData.append('photo', photo); 

return $http({
    url: PATH_REST_SERVICES + '/nomeServizio',
    headers: {"Content-Type": undefined },
    data: formData,
    method: "PUT"
});

将内容类型标头设置为 undefined 很重要.通常 $http service 将内容类型设置为 application/json代码>.当内容类型为 undefined 时,XHR API 将使用适当的 多部分边界.

It is important to set the content type header to undefined. Normally the $http service sets the content type to application/json. When the content type is undefined, the XHR API will automatically set the content type to multipart/form-data with the proper multi-part boundary.