如何使用Express Node.js上传图像文件并显示

我已经使用以下代码:

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');

任何人都可以帮助解决此问题。

回答:

您正在尝试使用multer的旧API。它改变了一段时间,请参阅文档以获取更多信息。

在您上载单个文件的特定情况下,您将删除该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

});

}

});

});

以上是 如何使用Express Node.js上传图像文件并显示 的全部内容, 来源链接: utcz.com/qa/404226.html

回到顶部