我是Mean和nodejs的新手。我有一个旧项目与旧依赖项。我正在尝试使用角度js将图像文件上传到服务器。但它不起作用。我不知道如何在客户端和服务器端检索图像文件数据,名称,类型等。
客户js
$scope.uploadFile = function(files,index) {
console.log("uploading file");
console.log("sticker index:" + index);
console.log("StickerGroupID:"+ $scope.stickergroup._id);
console.log("file:"+ files[0].name);
console.log("sticker : " + $scope.stickergroup.stickers[index].stickername );
$scope.stickergroup.stickers[index].stickerFileName = files[0].name ;
console.log("sticker path now:" +$scope.stickergroup.stickers[index].stickerFileName);
var fd = new FormData();
fd.append("file", files[0]);
fd.append("filename", files[0].name);
//put an upload file to temp location.
$http.post("/stickergroups/uploadstickers", fd, {
// withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity});
服务器js
exports.uploadTempFile = function(req, res) {
console.log("uploading start");
console.log("file required :" +req.files);
var imagefile = req.files.file;
var tempDirectorySticker = tempDirectory + imagefile.originalFilename;
console.log("temp directory" + tempDirectorySticker );
fs.readFile(imagefile.path, function (err, data) {
fs.writeFile(tempDirectorySticker, data, function (err) {
res.redirect("back");
});
});};
req.files导致“未定义”。
谢谢
答案 0 :(得分:1)
您必须实际使用文件上传middleware
来获取快递以解包该部分请求。来自multer
文档:
var express = require('express')
var multer = require('multer')
var app = express()
app.use(multer({ dest: './uploads/'}));
console.log(req.body)
console.log(req.files)
答案 1 :(得分:0)
确保使用您正在使用中间件进行多部分/表单数据,例如multer
https://github.com/expressjs/multer。
另外,检查是否存在CORS错误。你可以安装cors npm模块来解决这个问题。 https://www.npmjs.com/package/cors