我尝试在后端使用sails.js在节点(multiparty)+ angular(angular-file-upload)上执行简单的上传文件。似乎前端正确地将文件发送到后端,但它出现后端没有收到任何信息或响应无效请求(不一致)。 form.parse部分用空字段和文件响应。我几乎被困在这里,谷歌搜索几小时找出多方的问题,但我找不到任何有用的信息。任何建议都会很感激
请求标题:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:76632
Content-Type:multipart/form-data; boundary=----WebKitFormBoundary7iH8B208bfkavrKt
Cookie:sails.sid=s%3AY9YwxQC90Sq7pc3bp-scW7EH.%2B%2FYHfrTXCUzfPOBpeEt7VFH6Npw3s05Rqyfgu6DHVdg
Host:localhost:1337
Origin:http://localhost:1337
Referer:http://localhost:1337/kirill
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36
Request Payload
------WebKitFormBoundary7iH8B208bfkavrKt
Content-Disposition: form-data; name="file"; filename="10923270_813578785376550_5210357694589684637_n.jpg"
Content-Type: image/jpeg
------WebKitFormBoundary7iH8B208bfkavrKt--
后端(具有多方的节点):
upload: function(req, res) {
var multiparty = require('multiparty');
var fs = require('fs');
var util = require('util');
var form = new multiparty.Form();
form.parse(req, function(err, fields, file){
if (err) {
res.writeHead(400, {'content-type': 'text/plain'});
res.end("invalid request: " + err.message);
return;
}
console.log(file);
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received fields:\n\n '+util.inspect(fields));
res.write('\n\n');
res.end('received files:\n\n '+util.inspect(file));
});
}
前端(带角度文件上传的角度):
$scope.upload = function () {
//console.log($scope.file);
if ($scope.file.data[0]){
console.log("uploading file..");
console.log($scope.file.data[0]);
$upload.upload({
url: 'api/v1.0/upload',
method: 'POST',
file: $scope.file.data[0]
}).progress(function(evt){
var progressPercentage = parseInt(100.0 * evt.loaded/evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.name);
}).success(function (data, status, headers, config){
console.log('file ' + config.file.name + ' uploaded. Response: ' + data.status);
});
}
}
答案 0 :(得分:2)
我改为在后端使用skipper,默认情况下带有sas js。在向后端发送post请求时,我需要将fileFormDataName
指定为filename
,我可以使用该名称在后端获取req.file('filename')。
答案 1 :(得分:0)
将content-type设置为multipart:
$upload.upload({
url: 'api/v1.0/upload',
method: 'POST',
data: { 'Content-Type': 'multipart/form-data' },
file: $scope.file.data[0]
}).progress(function(evt){
var progressPercentage = parseInt(100.0 * evt.loaded/evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.name);
}).success(function (data, status, headers, config){
console.log('file ' + config.file.name + ' uploaded. Response: ' + data.status);
});