gpt4 book ai didi

node.js - 无法将文件从 Angularjs 上传到 Expressjs

转载 作者:搜寻专家 更新时间:2023-11-01 00:25:01 25 4
gpt4 key购买 nike

我正在尝试将图像从 AngularJS 界面上传到 nodejs 服务器 (expressjs)。(我正在使用 mean.io )

每次我上传一些东西,req.body 记录“{}”和 req.files 记录“undefined”

我正在使用 angular-file-upload AngularJS 中的指令

客户端代码:

$scope.onFileSelect = function() {
console.log($files);
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'map/set',
method: 'POST',
headers: {'enctype': 'multipart/form-data'},
data: {myObj: $scope.myModelObj},
file: file,

}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
};

服务器端代码

var app = express();
require(appPath + '/server/config/express')(app, passport, db);
app.use(bodyParser({uploadDir:'./uploads'}));
app.post('/map/set', function(req, res) {
console.log(req.body);
console.log(req.files);
res.end('Success');
});

*****编辑*****

HTML 代码

<div class="row">
<input id="file" type="file" ng-file-select="onFileSelect()" >
</div>

手工构建请求

$scope.onFileSelect = function() {
//$files: an array of files selected, each file has name, size, and type.
//console.log($files);

var xhr = new XMLHttpRequest();
// not yet supported in most browsers, some examples use
// this but it's not safe.
// var fd = document.getElementById('upload').getFormData();

var fd = new FormData();
var files = document.getElementById('myfileinput').files;
console.log(files);
for(var i = 0;i<files.length; i++) {
fd.append("file", files[i]);
}

/* event listeners */
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("abort", uploadCanceled, false);

function uploadComplete(){
console.log("complete");
}

function uploadProgress(){
console.log("progress");
}

function uploadFailed(){
console.log("failed");
}

function uploadCanceled(){
console.log("canceled");
}

xhr.open("POST", "map/set");

xhr.send(fd);


};

最佳答案

最新版本的 mean.io 不包括 express 4.x 作为依赖项。在迁移 express 3 到 4 的文档中,您可以阅读,express 将不再使用连接中间件。在这里阅读更多信息:https://github.com/visionmedia/express/wiki/Migrating-from-3.x-to-4.xbody-parser模块只处理 urlencoded 和 json 主体。这意味着对于多部分主体(文件上传),您需要一个额外的模块,如 busboyformadible .这是我如何将 angular-file-upload 与 busboy 一起使用的示例:AngularJS 的东西:

$upload.upload({
url: '/api/office/imageUpload',
data: {},
file: $scope.$files
}) …

我写了一个小助手模块来更轻松地处理 busboy 的上传。它的代码不是很干净,但可以完成工作:

var env = process.env.NODE_ENV || 'development';
var Busboy = require('busboy'),
os = require('os'),
path = require('path'),
config = require('../config/config')[env],
fs = require('fs');

// TODO: implement file size limit

exports.processFileUpload = function(req, allowedExtensions, callback){
var busboy = new Busboy({ headers: req.headers });
var tempFile = '';
var fileExtenstion = '';
var formPayload = {};

busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
fileExtenstion = path.extname(filename).toLowerCase();
tempFile = path.join(os.tmpDir(), path.basename(fieldname)+fileExtenstion);
file.pipe(fs.createWriteStream(tempFile));
});

busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
var jsonValue = '';

try {
jsonValue = JSON.parse(val);
} catch (e) {
jsonValue = val;
}

formPayload[fieldname] = jsonValue;
});

busboy.on('finish', function() {
if(allowedExtensions.length > 0){
if(allowedExtensions.indexOf(fileExtenstion) == -1) {
callback({message: 'extension_not_allowed'}, tempFile, formPayload);
} else {
callback(null, tempFile, formPayload)
}
} else {
callback(null, tempFile, formPayload)
}
});

return req.pipe(busboy);
}

在我的 Controller 中,我可以这样使用模块:

var uploader = require('../helper/uploader'),
path = require('path');


exports.uploadEmployeeImage = function(req,res){
uploader.processFileUpload(req, ['.jpg', '.jpeg', '.png'], function(uploadError, tempPath, formPayload){

var fileExtenstion = path.extname(tempPath).toLowerCase();
var targetPath = "/exampleUploadDir/testFile" + fileExtenstion;

fs.rename(tempPath, targetPath, function(error) {
if(error){
return callback("cant upload employee image");
}

callback(null, newFileName);
});
});
}

关于node.js - 无法将文件从 Angularjs 上传到 Expressjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23606289/

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