【问题标题】:uploading file using multer is not working fully (NodeJS)使用 multer 上传文件无法正常工作(NodeJS)
【发布时间】:2016-11-17 23:26:26
【问题描述】:

我正在使用 NodeJS express (MVC),我正在尝试上传图片。我正在尝试将图像存储在上传文件夹中,但没有显示任何内容。当我 console.log(req.files) 时,我得到以下信息(req.buffer 打印出一长串的两位数字和字母)。我如何获得这个以将图像保存在文件夹中?

 [ 
   { 
     fieldname: 'file',
     originalname: 'thumbnail.jpg',
     encoding: '7bit',
     mimetype: 'image/jpeg',
     buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 84 00 09 06 07 0d 0d 10 0e 10 0d 0e 0d 0d 0d 0e 10
 0f 0d 0d 0e 0d 0d 0f  0e 0e 0e ... >,
     size: 1347 
   } 
]

HTML:

<form action="/bars/upload" method = 'post' enctype="multipart/form-data">
   <label for='file'>Upload Image</label>
   <input type="file" name="file" accept="image/*"/>
   <input type="submit" name='submit' value="submit"/>
</form>

节点 JS

var multer  = require('multer'); 
var upload = multer({ dest:'../public/uploads/' });

router.post('/bars/upload', function (req, res, next) { 
    console.log(req.files);     
    res.send(req.files); 
});

【问题讨论】:

    标签: javascript node.js express file-upload


    【解决方案1】:

    multer 基本上是一个中间件,用于上传文件或转换为稍后可以在处理程序中使用的某种格式。所以,从examples,你可以在你的情况下这样做:

    var multer = require('multer'); 
    var upload = multer({ dest:'../public/uploads/' });
    
    router.post('/bars/upload', upload.single('someFile') ,function (req, res, next) {
    
        // if you're here, the file should have already been uploaded
    
        console.log(req.files); 
        console.log(req.body);// {"someParam": "someValue"}
        res.send(req.files); 
    });
    

    上传.html

    <form action="/bars/upload" method = 'post' enctype="multipart/form-data">
        <label for='file'>Upload Image</label>
        <input type="file" name="someFile" accept="image/*"/>
        <input type="hidden" name="someParam" value="someValue"/>
        <input type="submit" name='submit' value="submit"/>
    </form>
    

    如果这样不行,你可以使用命令行调试,这通常可以帮助我确定是服务器故障还是客户端故障。

    curl --form "someFile=@/path/to/file" -X POST http://localhost:3000/bars/upload
    

    添加 -I 选项以显示详细响应。

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。我使用 Postman 对我的节点应用程序进行查询。当我删除 http 标头 Content-Type(它被设置为 urlencoded 形式)时,问题解决了。

      【讨论】:

      • 这是救命稻草!
      • 我什至没有设置 http 标头,但我将它保存为一种奇怪的格式我已经在这里声明了这个问题stackoverflow.com/questions/49544671/…
      • @ChinmayGhag 如果您使用邮递员上传文件,则无需设置自己的标题,因为当您选择form-data 作为发布方法时,这些标题会自动为您设置。
      【解决方案3】:

      我有同样的问题 在 dest:'../public/uploads/' 中删除 ../ 像这样写 dest:'公共/上传/' 就是这样

      【讨论】:

        猜你喜欢
        • 2019-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多