0
HTMLフォームと実行中のExpress Webサーバーとの間にファイルを渡そうとしています。方程式からAngularを削除し、通常のPOSTでフォームを送信すると、Expressはファイルを受信します。角度アプリケーションからExpress Webサーバーへのファイルの提出
マイ形式:
<form ng-submit="addEntry()" enctype="multipart/form-data">
<fieldset>
<legend>Upload Image</legend>
<div class="form-group">
<label>
mmol/L:
<input type="number" ng-model="mmol">
</label>
</div>
<div class="form-group">
<label>
Carbs:
<input type="number" ng-model="carbs">
</label>
</div>
<div class="form-group">
<label>
Image:
<input type="file" name="file" file-upload file-changed="setFile(file)">
</label>
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</fieldset>
私のFileUploadディレクティブ:
app.directive('fileUpload', function() {
return {
scope: {
fileChanged: '&'
},
link: function(scope, elem, attrs) {
elem.bind('change', function(event) {
scope.fileChanged({
file: event.target.files[0]
});
});
}
}
});
マイコントローラー:
$scope.addEntry = function() {
APIFactory.addEntry($scope.mmol, $scope.carbs, $scope.file);
}
APIFactory:
app.factory('APIFactory', ['$http', function($http) {
return {
addEntry: function(mmol, carbs, file) {
var reading = {
mmol: mmol,
carbs: carbs,
file: file
};
console.log(reading);
$http({
method: 'POST',
url: 'http://localhost:1337/upload',
data: reading
}).then(function success(response) {
console.log(response);
}, function error(err) {
console.log(err);
})
}
}
}]);
エクスプレスサーバ:
app.post('/upload', upload.single('image'), function(req, res) {
var image = req.file;
console.log(image);
});
にconsole.log(読み取り)の結果APIFactoryで:
Object {mmol: 10, carbs: 10, file: File}
私エクスプレスServerではconsole.log(画像)の結果:
undefined
アプリケーションのクライアント側では、Fileオブジェクトが渡されます。私のサーバーにそれを渡そうとすると問題が発生します。誰がなぜこれが起こっているのかについての洞察を提供することはできますか?私はFormData
app.factory('APIFactory', ['$http', function($http) {
return {
addEntry: function(mmol, carbs, file) {
var fd = new FormData();
fd.append('mmol', mmol);
fd.append('carbs', carbs);
fd.append('file', file);
$http({
method: 'POST',
url: 'http://localhost:1337/upload',
data: fd,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function success(response) {
console.log(response);
}, function error(err) {
console.log(err);
})
}
}
}]);
の助けを借りて解決策を見つけた