在没有公共URL的情况下从Node.js中的Google Cloud Storage检索图像

时间:2017-04-02 17:17:45

标签: node.js google-cloud-storage

我正在尝试将图像返回给我的用户以在DOM上查看而不创建图像的公共链接(此路由受到我的服务器的auth保护,然后才能恢复图像)。这是我到目前为止所尝试过的,但这可能是错误的方法。

我正在关注带有Node.js指南的Google云端存储,以便将图片上传添加到我的项目中。我现在上传工作,图像保存在Google云端存储中。该指南显示了如何检索公共网址:

https://cloud.google.com/nodejs/getting-started/using-cloud-storage

我正在尝试使用文件流而不是公共网址,以便我的图片不会公开。我猜它看起来类似于这个存储库中的流: https://github.com/GoogleCloudPlatform/google-cloud-node

但是我试图在HTTP响应上返回图像而不是简单地将它们本地存储在我的文件系统上。

我的客户端Javascript正在获得一个看起来像一个巨大的blob的响应。 ����JFIF���Photoshop 3.08BIM�元数据让我觉得这实际上是正确的图像,但我不确定如何将其恢复为看起来像图像。

这是我的节点服务器文件。上传到Google云端存储/post正在运行,我可以看到正在添加的图片。

Google Cloud Storage Upload Working

/get正在返回看起来像一个巨大的斑点,看起来像是我想要的图像(就像我不知道如何转换的奇怪斑点)。

我的代码如下所示:

var express = require('express');
var router = express.Router();
const Multer = require('multer');
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
  }
});

const Storage = require('@google-cloud/storage');

const storage = Storage({
  keyFilename: 'server/firebase-service-account.json',
  projectId: process.env.FIREBASE_PROJECT_ID
});

const bucket = storage.bucket(process.env.FIREBASE_STORAGE_BUCKET);

// Process the file upload and upload to Google Cloud Storage.
router.post('/', multer.single('file'), (req, res, next) => {
  console.log('req.body', req.body);
  console.log('req.file', req.file);
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream();

  blobStream.on('error', (err) => {
    next(err);
    return;
  });

  blobStream.on('finish', () => {
    res.status(200).send('The image has been successfully uploaded to google cloud storage');
  });

  blobStream.end(req.file.buffer);
});

router.get('/', function (req, res, next) {
  var stream = bucket.file('Toast.jpg').createReadStream();

  stream.pipe(res);

  stream.on('data', function (data) {
    res.write(data);
  });

  stream.on('error', function (err) {
    console.log('error reading stream', err);
  });

  stream.on('end', function () {
    res.set({
      "Content-Disposition": 'attachment; filename="Toast.jpg"',
      "Content-Type": 'image/jpg'
    });
    res.end();
  });
});

module.exports = router;

这是否接近?有没有更好的方法来使用我的身份验证来保护我的图像?

2 个答案:

答案 0 :(得分:1)

我正在考虑错误的方式。我需要将<img src=""路由到正确的位置。

HTML

<img src="/uploads/1234">

服务器节点

var express = require('express');
var router = express.Router();
const Multer = require('multer');
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
  }
});

const Storage = require('@google-cloud/storage');

const storage = Storage({
  keyFilename: 'server/firebase-service-account.json',
  projectId: process.env.FIREBASE_PROJECT_ID
});

const bucket = storage.bucket(process.env.FIREBASE_STORAGE_BUCKET);

// Process the file upload and upload to Google Cloud Storage.
router.post('/', multer.single('file'), (req, res, next) => {
  console.log('req.body', req.body);
  console.log('req.file', req.file);
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream();

  blobStream.on('error', (err) => {
    next(err);
    return;
  });

  blobStream.on('finish', () => {
    res.status(200).send('The image has been successfully uploaded to google cloud storage');
  });

  blobStream.end(req.file.buffer);
});

router.get('/:imageId', function (req, res, next) {
  var stream = bucket.file('Toast.jpg').createReadStream();

  res.writeHead(200, {'Content-Type': 'image/jpg' });

  stream.on('data', function (data) {
    res.write(data);
  });

  stream.on('error', function (err) {
    console.log('error reading stream', err);
  });

  stream.on('end', function () {
    res.end();
  });
});

module.exports = router;

我仍然希望得到关于这是否是解决此问题的正确方法的反馈。 (显然,硬编码需要进行。)

答案 1 :(得分:1)

获取图像部分现在可以使用“下载”功能完成,这是我在Typescript中的代码段:

  async downloadImage(filename: string): Promise<Buffer> {
    try {
       // this.storageHandler is the Storage variable created with new Storage();
      const file = this.storageHandler.bucket(this.bucketName).file(filename);
      const imageDownloaded = await file.download();
      return imageDownloaded[0];
    } catch (err) {
      console.log('Handle the error as you want');
    }
    throw Error('Error while downloading image');
  }
}