【问题标题】:convert Base64 Image with expressjs使用 expressjs 转换 Base64 图像
【发布时间】:2020-03-12 12:01:39
【问题描述】:

将图像从 FTP 服务器转换为 Base64 时出错。例如:

router.get('/getPhoto', async function (req, res) {
    const ftp = new PromiseFtp();
    data='';
    try {
      await ftp.connect({ host: varFtp.host, user: varFtp.username, password: varFtp.password })
      const stream = await ftp.get('store/photo1.jpeg');

      data += stream.read().toString('base64');
      console.log(data)  -> this is erorr

      await new Promise((resolve, reject) => {
         res.on('finish', resolve);
         stream.once('error', reject);
         stream.pipe(res)
      });
     } catch(e) {
       console.error(e);
     } finally {
       await ftp.end();
     }
}); 

我有错误TypeError: Cannot read property 'toString' of null。我的最终目标是使用 json 格式将 Base64 发送给客户端

【问题讨论】:

    标签: node.js express base64


    【解决方案1】:

    您只需要在发送之前对 base64 编码进行管道传输。像这样使用base64-stream 可以简化这一点

    const {Base64Encode} = require("base64-stream");
    
    
    app.get("/getPhoto", async function (req, res) {
      const ftp = new PromiseFtp();
      data = "";
      try {
        await ftp.connect({ host: varFtp.host, user: varFtp.username, password: varFtp.password })
        const stream = await ftp.get('store/photo1.jpeg');
    
        await new Promise((resolve, reject) => {
          res.on("finish", resolve);
          stream.once("error", reject);
          stream.pipe(new Base64Encode()).pipe(res); // see here
        });
      } catch (e) {
        console.error(e);
      } finally {
        await ftp.end();
      }
    });
    
    

    【讨论】:

      【解决方案2】:
      function getImage(imageUrl) {
      var options = {
          url: `${imageUrl}`,
          encoding: "binary"
      };
      
        return new Promise(function (resolve, reject) {
          request.get(options, function (err, resp, body) {
              if (err) {
                  reject(err);
              } else {
                  var prefix = "data:" + resp.headers["content-type"] + ";base64,";
                  var img = new Buffer(body.toString(), "binary").toString("base64");
                  //  var img = new Buffer.from(body.toString(), "binary").toString("base64");
                  var dataUri = prefix + img;
                  resolve(dataUri);
              }
          })
      })
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-09
        • 2016-09-22
        • 2021-07-19
        • 2015-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多