【问题标题】:Reading buffer data from uploaded file in NodeJS从 NodeJS 中上传的文件中读取缓冲区数据
【发布时间】:2020-04-27 14:28:17
【问题描述】:

我正在使用“express”模块上传文件。我必须使用node-exif 读取上传图像的EXIF 数据。我不想将文件存储在磁盘上,并且上面的模块支持从缓冲区读取 EXIF 数据。我需要从上传的图像中读取缓冲区数据。这是上传代码:

var express = require('express');
var app = express();
var fs = require('fs');
var multiparty = require("multiparty");

module.exports.UploadImage = function (req, res, next) {
    // Handle request as multipart  
    if (!req.files)
        return res.status(400).send('No files were uploaded.');  

    var sampleFile = req.files.uploadedFile;
    //Here I need to have the buffer.
    res.send('Done!');
}

由于我是 Node 世界的新手,有人可以帮我获取缓冲区数据吗?

【问题讨论】:

  • 如果不将文件存储在磁盘上,您将如何使用 node-exif?它似乎只提供从磁盘上的文件处理 exif 的能力....

标签: node.js nodejs-stream


【解决方案1】:

以下是获取缓冲区的方法:

var express = require("express");
const fileUpload = require('express-fileupload');
var app = express();
app.use(fileUpload());

app.post("/upload", (req, res) => {

   console.log(req.files.file);

   res.status(200).send('Success!!!');
});

控制台输出:

{
  name: 'task.txt',
  data: <Buffer ef bb bf 37 38 37 39 34 38 36 34 0d 0a 37 38 37 39 ... 57 more bytes>,
  size: 107,
  encoding: '7bit',
  tempFilePath: '',
  truncated: false,
  mimetype: 'text/plain',
  md5: '6e37e5195b2acfcac7713952ba080095',
  mv: [Function: mv]
}

data 参数是您所需要的。 您可以将缓冲区解析为字符串,如下所示:

   console.log(req.files.file.data.toString('utf8'));

【讨论】:

    【解决方案2】:

    我想这就是你要找的东西

      module.exports.UploadImage = function (req, res, next) {
        // Handle request as multipart  
        if (!req.files)
            return res.status(400).send('No files were uploaded.');  
    
        var sampleFile = req.files.uploadedFile;
        //Here I need to have the buffer.
        var chunks = []
        req.on('data', function (chunk) {
            // reads chunks of data in Buffer
            console.log(chunk) // Prints <Buffer 8a 83 ef ... >
            chunks.push(chunk)
        })
    
        res.send('Done!');
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-08
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      相关资源
      最近更新 更多