gpt4 book ai didi

javascript - 如何使用express nodejs上传图像文件并显示

转载 作者:IT老高 更新时间:2023-10-28 23:15:20 26 4
gpt4 key购买 nike

我使用了以下代码:

文件上传.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>

文件上传.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)
})

我已经使用上面的这些代码进行文件上传但是当在终端中使用 node fileupload.js 执行时,我收到类型错误 TypeError('app.use() requires middleware functions');

谁能帮忙解决这个问题。

最佳答案

您正在尝试使用 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
});
}
});
});

关于javascript - 如何使用express nodejs上传图像文件并显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36477145/

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