如何在云函数

时间:2018-05-03 20:14:23

标签: firebase http google-cloud-functions http-status-code-413

我正在尝试调用发送大于50Mb图像的Google云端功能。云功能的目的是调整图像大小并将其上传到谷歌云存储。

但是,当我将HTTP帖子发送到我的云功能时,我收到以下错误:413请求实体太大

有没有人对此错误有任何解决方法?我可以增加http请求大小限制吗?

2 个答案:

答案 0 :(得分:2)

HTTP触发器上载和下载有效负载大小的限制为documented at 10MB。没有办法增加此限制,但您可以file a feature request解释为什么应该增加限制。

答案 1 :(得分:0)

您可以让客户端直接上传到存储。 authinticated到他自己的用户文件夹和安全规则,将文件大小限制为你想要的任何大小的临时文件夹。

然后让云功能触发器开始调整图像大小。 并在完成后删除原始图像。

我附上了我的代码示例 - 你应该在转换后添加一个文件删除...



/**
 * When an image is uploaded in the Storage bucket We generate a thumbnail automatically using
 * ImageMagick.
 * After the thumbnail has been generated and uploaded to Cloud Storage,
 * we write the public URL to the Firebase Realtime Database.
 */
exports.generateThumbnail = functions.storage.object().onFinalize((object) => {
  console.log('Generated Started');

  // File and directory paths.
  const filePath = object.name;
  const contentType = object.contentType; // This is the image MIME type
  const fileDir = path.dirname(filePath);
  const fileName = path.basename(filePath);
  const thumbFilePath = path.normalize(path.join(fileDir, `${THUMB_PREFIX}${fileName}`));
  const tempLocalFile = path.join(os.tmpdir(), filePath);
  const tempLocalDir = path.dirname(tempLocalFile);
  const tempLocalThumbFile = path.join(os.tmpdir(), thumbFilePath);

  // Exit if this is triggered on a file that is not an image.
  if (!contentType.startsWith('image/')) {
    console.log('This is not an image.');
    deleteImage(filename);
    return null;
  }

  // Exit if the image is already a thumbnail.
  if (fileName.startsWith(THUMB_PREFIX)) {
    console.log('Already a Thumbnail.');
    deleteImage(filename);
    return null;
  }

  // Cloud Storage files.
  const bucket = gcs.bucket(object.bucket);
  const file = bucket.file(filePath);
  const thumbFile = bucket.file(thumbFilePath);
  const metadata = {
    contentType: contentType,
    // To enable Client-side caching you can set the Cache-Control headers here. Uncomment below.
    'Cache-Control': 'public,max-age=3600',
  };
  // Create the temp directory where the storage file will be downloaded.
  return mkdirp(tempLocalDir).then(() => {
    console.log('DL Started');

    // Download file from bucket.
    return file.download({
      destination: tempLocalFile
    });
  }).then(() => {
    console.log('The file has been downloaded to', tempLocalFile);
    // Generate a thumbnail using ImageMagick.
    return spawn('convert', [tempLocalFile, '-thumbnail', `${THUMB_MAX_WIDTH}x${THUMB_MAX_HEIGHT}>`, tempLocalThumbFile], {
      capture: ['stdout', 'stderr']
    });
  }).then(() => {
    console.log('Thumbnail created at', tempLocalThumbFile);
    // Uploading the Thumbnail.
    return bucket.upload(tempLocalThumbFile, {
      destination: thumbFilePath,
      metadata: metadata
    });
  }).then(() => {
    console.log('Thumbnail uploaded to Storage at', thumbFilePath);
    // Once the image has been uploaded delete the local files to free up disk space.
    fs.unlinkSync(tempLocalFile);
    fs.unlinkSync(tempLocalThumbFile);
    // Get the Signed URLs for the thumbnail and original image.
    const config = {
      action: 'read',
      expires: '03-01-2500',
    };
    return Promise.all([
      thumbFile.getSignedUrl(config),
      // file.getSignedUrl(config),
    ]);
  }).then((results) => {
    console.log('Got Signed URLs.');
    const thumbResult = results[0];
    // const originalResult = results[1];
    const thumbFileUrl = thumbResult[0];
    // const fileUrl = originalResult[0];
    // Add the URLs to the Database
    const uid = getUidFromFilePath(fileDir);
    if (!uid) return null;

    return Promise.all([
      admin.auth().updateUser(uid, {
        photoURL: thumbFileUrl
      }),
      admin.database().ref(`/users/${uid}/profile/photoURL`).set(thumbFileUrl)
    ]);
  }).then(() => console.log('Thumbnail URLs saved to database.'));
});