gpt4 book ai didi

javascript - 使用 $http 上传文件

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:56 25 4
gpt4 key购买 nike

这道题是不是太难了?

我的客户端代码包含发布数据变量,并且想知道如何将文件数据添加到 $http.post

我看过一些示例,它们要么使用自定义指令,要么使用手动表单提交,这两种情况都是我想要的。

客户端:

<input type="file" id="photo">
//file can be accessed using
var photo = document.getElementById("photo").files[0];
$scope.data.photo = photo

或者

var formData = new FormData();
formData.append("photo", photo);
formData.append("title", $scope.data.title);
this.delegate.insert(formData);

已发送至服务

$http.post("/admin/speakers/?" + data, token.body) //token.body = $scope.data
.success(function(data, status, headers, config) {
})
.error(function(data, status, headers, config) {
});

期望输出服务器端(使用 POSTMAN - REST 客户端生成)

console.log(request.files, request.body);

{ photo:
{ fieldname: 'photo',
originalname: '01.jpg',
name: 'fbb54fa6d588ac253ca7dab08a904356.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
path: '/var/folders/jg/hkmz0fdn64g8w1jgf60j2lcw0000gn/T/fbb54fa6d588ac253ca7dab08a904356.jpg',
extension: 'jpg',
size: 12279,
truncated: false,
buffer: null } }

{ name: 'SA',
title: 'Dev',
company: 'CA',
bio: 'some bio',
twitter: '@twitter',
sessionId: '1' }

最佳答案

尝试将 Content-Type header 设置为 undefined 并将 transformRequest 设置为 angular.identity(以不序列化 FormData 对象):

$http.post("/admin/speakers/?" + data, token.body, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}).success(function(data, status, headers, config) {

}).error(function(data, status, headers, config) {

});

Angular’s default transformRequest function will try to serialize our FormData object, so we override it with the identity function to leave the data intact. Angular’s default Content-Type header for POST and PUT requests is application/json, so we want to change this, too. By setting ‘Content-Type’: undefined, the browser sets the Content-Type to multipart/form-data for us and fills in the correct boundary. Manually setting ‘Content-Type’: multipart/form-data will fail to fill in the boundary parameter of the request.

(https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs)

关于javascript - 使用 $http 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30490021/

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