我使用了以下代码:
fileupload.html
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="http://127.0.0.1:8081/file_upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
fileupload.js:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
//console.log(multer);
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));
app.get('/fileupload.html', function (req, res) {
res.sendFile( __dirname + "/" + "fileupload.html" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
我已经使用上面的代码进行文件上传但是当在终端使用节点fileupload.js执行时我收到类型错误TypeError('app.use() requires middleware functions');
任何人都可以帮助解决这个问题。
答案 0 :(得分:13)
您正在尝试使用multer
的旧API。它改变了一段时间,请参阅documentation以获取更多信息。
在上传单个文件的特定情况下,您会删除app.use(multer({ ... }))
行,而是使用.single()
和req.file
,如:
var upload = multer({ dest: '/tmp/'});
// File input field name is simply 'file'
app.post('/file_upload', upload.single('file'), function(req, res) {
var file = __dirname + '/' + req.file.filename;
fs.rename(req.file.path, file, function(err) {
if (err) {
console.log(err);
res.send(500);
} else {
res.json({
message: 'File uploaded successfully',
filename: req.file.filename
});
}
});
});
答案 1 :(得分:4)
Multer 将一个body对象和一个或多个文件对象添加到请求对象中。 body对象包含表单文本字段的值,文件或files对象包含通过表单上传的文件。
使用此代码,希望这对您有帮助。
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
var upload = multer({ dest: '/tmp' })
app.get('/fileupload.html', function (req, res) {
res.sendFile( __dirname + "/" + "fileupload.html" );
})
app.post('/file_upload', upload.single("file"), function (req, res) {
var file = __dirname + "/" + req.file.originalname;
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.error( err );
response = {
message: 'Sorry, file couldn\'t be uploaded.',
filename: req.file.originalname
};
}else{
response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
}
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
答案 2 :(得分:1)
以上解决方案对我没有用,所以我使用了存储方法:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var ext = require('path').extname(file.originalname);
ext = ext.length>1 ? ext : "." + require('mime').extension(file.mimetype);
require('crypto').pseudoRandomBytes(16, function (err, raw) {
cb(null, (err ? undefined : raw.toString('hex') ) + ext);
});
}
});
var upload = multer({ storage: storage });
app.post('/file_upload', upload.any(), function (req, res, next) {
res.send(req.files);
})
答案 3 :(得分:0)
它对我有用
var express = require('express'),
http = require('http'),
formidable = require('formidable'),
fs = require('fs'),
path = require('path');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer({ dest: '/tmp/'});
var app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
var server = app.listen(3000, function() {
console.log('leistening on port', server.address().port);
})
app.post('/upload', upload.single('file'), function(req, res) {
var file = 'uploads' + '/' + req.file.originalname;
fs.rename(req.file.path, file, function(err) {
if (err) {
res.send(500);
} else {
res.json({
message: 'File uploaded successfully',
filename: req.originalname
});
}
});
});
&#13;
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<form action="http://127.0.0.1:3000/upload" enctype="multipart/form-data" method="post">
<input type="text" name="title">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
&#13;
答案 4 :(得分:-1)
似乎保留原始文件名或扩展名并不安全,我发现/制作了此代码,可以通过在文件网址中添加.jpg来直接显示图像:
restapi.get('/uploads/:id', function (req, res) {
var storedMimeType = 'image/jpeg';
res.setHeader('Content-Type', storedMimeType)
fs.createReadStream(path.join('./uploads/', req.params.id).replace(/\.[^/.]+$/, "")).pipe(res)
})