繁体   English   中英

node js使用multer上传图像并保存到firebase存储

[英]node js uploading image with multer and save to firebase storage

我的 ejs 前端代码如下

<form action='/powerLink' method='post' enctype='multipart/form-data'> <input type='file' name='file'> <input type='submit' value='fileupload'> </form>

和我的 js 代码,其中接收文件如下

var storagee=firebase.storage().ref("test");
 app.post("/powerLink", multer.single('file'),function(req,res){
  let file = req.file;
  if(file){
    console.log(file);
     storage.put(file);
  }

当我 console.log(file) 它有如下值 { fieldname: '

file',
  originalname: 'appiicon.png',
  encoding: '7bit',
  mimetype: 'image/png',
  buffer:
   <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 e1 00 00 00 e1 08 06 00 00 00 3e b3 d2 7a 00 00 00 19 74 45 58 74 53 6f 66 74 77 61 72 65 00 ... >,
  size: 15966 }

我认为它会直接保存到我的存储和文件夹“test”中,然后将图像保存到该文件夹​​中。 但什么也没发生。

我无法猜测不将图像文件上传到 firebase 上的存储的原因是什么

在使用 firebase admin sdk 之前,我已经这样做了(打字稿):

async function uploadFile(file: Express.Multer.File, directory: string, fileName: string): Promise<string> {
  const bucket = firebaseAdmin.storage().bucket();
  const fullPath = `${directory}/${fileName}`;
  const bucketFile = bucket.file(fullPath);

  await bucketFile.save(file.buffer, {
    contentType: file.mimetype,
    gzip: true
  });

  const [url] = await bucketFile.getSignedUrl({
    action: "read",
    expires: "01-01-2050"
  });

  return url;
}

我有一个相关的问题。 传入文件对象返回错误: TypeError: Cannot read property 'byteLength' of undefined

您应该像这样传入 buffer 属性,而不是传入文件对象:

var storagee=firebase.storage().ref("test");
app.post("/powerLink", multer.single('file'),function(req,res){
    var file = req.file;
    if(file){
    console.log(file);
    let metadata = {contentType: file.mimetype, name: file.originalname}
    storage.put(file.buffer, metadata);
}

在此之后,我收到了 XMLHttpRequest 错误。 我安装了 xhr2 模块。 https://github.com/pwnall/node-xhr2

npm install xhr2

然后,如果您必须访问多个文件中的存储,您可以在索引/主文件中添加代码

global.XMLHttpRequest = require("xhr2");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM