所以我试图将一个mp3文件上传到NodeJS服务器。我正在查看文件数据和所有内容,所以我知道我的模型是正确的,但每次发送http帖子时,都会收到无效的JSON错误。这很令人困惑,因为我已经将内容类型设置为undefinded和multipart / form-data,无论我何时进入控制台,我仍然会在请求标头中看到content-type设置为application / json。这是我用来上传的代码:
模板:
<form>
<div class="form-group">
<label name="type-label" for="type">Type</label>
<select name="type" ng-model="data.type">
<option value="music">Music</option>
<option value="image">Image</option>
<option value="video">Video</option>
</select>
</div>
<div class="form-group">
<label name="name-label" for="name">Name</label>
<input type="text" name="name" ng-model="data.name" />
</div>
<div class="form-group">
<label name="description-label" for="description">Description</label>
<input type="text" name="description" ng-model="data.description" />
</div>
<div>
<input type="file" upload-file="file"/>
</div>
<div class="form-group">
<div class="btn btn-primary" ng-click="upload()">Select File</div>
</div>
</form>
服务:
angular.module('app').factory("UploadService", ['$http',
function($http) {
return {
upload: function (file, data) {
var fd = new FormData();
fd.append('file', file);
return $http({
method: 'POST',
url: '/upload/' + data.type,
data: fd,
transformRequest: angular.identity,
headers: {
'Content-Type': 'multipart/form-data'
}
})
.success(function(){
//Do something.
})
.error(function(){
//Do something.
});
}
}
}
]);
控制器:
angular.module('app').controller('UploadController', ['$scope', 'UploadService',
function($scope, UploadService) {
$scope.data = {};
$scope.upload = function() {
console.log($scope.file);
UploadService.upload($scope.file, $scope.data);
};
}
]);
最后我甚至写了一个小帮手配置来试图强制http帖子的默认内容类型。
助手:
angular.module('app').config(function($httpProvider) {
$httpProvider.defaults.headers.post = { 'Content-Type' : 'multipart/form-data' };
});
此时我很不知所措,所以任何建议/帮助都会非常感激。或者,如果有比这更简单的方法,一般上传MP3的任何提示。谢谢!
答案 0 :(得分:0)
试试这个
$httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';