gpt4 book ai didi

javascript - 使用 node.js 上传文件

转载 作者:搜寻专家 更新时间:2023-10-31 23:05:25 31 4
gpt4 key购买 nike

我有这段代码是为了使用 node.js 上传文件:

    app.use(express.bodyParser());
// or, as `req.files` is only provided by the multipart middleware, you could
// add just that if you're not concerned with parsing non-multipart uploads,
// like:
app.use(express.multipart());

app.get('/',function(req,res){
fs.readFile('uploadHTML.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});

});
app.post('/upload',function(req,res)
{
console.log(req.files);
fs.readFile(req.files.displayImage.path, function (err, data) {
// ...
var newPath = __dirname;
fs.writeFile(newPath, data, function (err) {
res.redirect("back");
});
});
});

这是 HTML 文件:

<html>
<head>
<title>Upload Example</title>
</head>
<body>

<form id="uploadForm"
enctype="multipart/form-data"
action="/upload"
method="post">
<input type="file" id="userPhotoInput" name="displayImage" />
<input type="submit" value="Submit">
</form>

<span id="status" />
<img id="uploadedImage" />


</body>
</html>

当我上传文件时,出现下一个错误:

TypeError: Cannot read property 'displayImage' of undefined at c:\NodeInstall\nodejs\express.js:42:22 at callbacks (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:164:37) at param (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:138:11) at pass (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:173:5) at Object.router (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:33:10) at next (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.expressInit [as handle] (c:\NodeInstall\nodejs\node_modules\express\lib\middleware.js:30:5) at next (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.query [as handle] (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\middleware\query.js:45:5)

可能是什么原因?

最佳答案

我建议你使用很棒的模块 https://github.com/domharrington/fileupload用于处理 node/express 中的文件上传。

var fileupload = require('fileupload').createFileUpload('/uploadDir').middleware

app.post('/upload', fileupload, function(req, res) {
// files are now in the req.body object along with other form fields
// files also get moved to the uploadDir specified
})

关于javascript - 使用 node.js 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23263307/

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