微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我无法使用以下 NodeJS 代码上传文件?

如何解决为什么我无法使用以下 NodeJS 代码上传文件?

我正在尝试在 NodeJS 中设计一个简单的应用程序,该应用程序通过 HTML 表单上传 CSV 文件。 仔细阅读了关于如何使用 NodeJS 上传文件YouTube 教程,我不明白为什么我的代码无法上传任何文件。我在 youtube 教程中的学习时间还没有超过 6:53 分钟。

在下面找到我的简单代码

const express = require('express');
const app = express();
const multer = require('multer');    

const fileStorageEngine = multer.diskStorage({
    destination: (req,file,cd)=> {
    cd(null,'./uploads')   
    },filename: (req,cb)=>{
    cb(null,Date.Now() + '--' + file.originalname);
    },});

const upload = multer({storage: 'fileStorageEngine'});

app.get('/',(req,res)=> {
    res.sendFile(__dirname +'/testDir/form.html' );
});

app.post('/uploads',upload.single('file'),res)=> {
    console.log(req.file);
    res.send('Single File Upload Success!');
});
    
app.listen('3600',()=> console.log('App is listening...')); 

...我的 HTML 表单代码如下所示:

enter image description here

http://localhost:3600/ 正确显示

enter image description here

我可以浏览到我选择的任何文件,然后单击将我定向到的提交按钮:

enter image description here

根据 6:53 分钟的 YouTubeuploads 文件夹现在应该包含上传文件, 但是,文件夹是空的!

另外,终端显示

enter image description here

...表明 console.log(req.file); 没有实际读入文件

我也尝试过使用 postman,这是结果的屏幕截图:

enter image description here

我尝试重新观看视频并仔细按照说明进行操作,但仍然无法解决问题。

请帮助我了解为什么上传不起作用以及如何解决此问题。 期待您的帮助。

解决方法

您已将 storage 字段设置为 string 而不是 multer.diskStorage 对象。

将其更改为:const upload = multer({storage: fileStorageEngine});

还要确保 Postman form-data 中的 key 值设置为 file,因为您使用的是 upload.single('file')

,

确保您的 html 表单中有 enctype="multipart/form-data"。另外,请确保您已正确设置名称。您能否也粘贴表单的代码?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。