nodejs回形针s3-如此困惑如何实现

时间:2019-07-15 21:43:01

标签: node.js amazon-s3 sequelize.js paperclip

我的问题:如何将图像上传到S3并使用NodeJS保存到用户记录中,就像Rails回形针宝石一样。

我相信这应该是过程,但是我还是很困惑这个程序包应该如何工作:

  1. 通过回形针接收图像并调整大小
  2. 保存或更新到S3
  3. 在数据库中保存文件信息user

我有一个rails postgres sql db,用户可以上传存储在S3中的图像,并用Paperclip gem重新格式化。存储方式如下:

irb(main):003:0> user.avatar
=> #<Paperclip::Attachment:0x000055b3e043aa50 @name=:avatar, 
@name_string="avatar", @instance=#<User id: 1, email: 
"example@gmail.com", created_at: "2016-06-11 22:52:36", 
updated_at: "2019-06-16 17:17:16", first_name: "Clarissa", 
last_name: "Jones", avatar_file_name: "two_people_talking.gif", 
avatar_content_type: "image/gif", avatar_file_size: 373197, 
avatar_updated_at: "2019-06-16 17:17:12", @options={:convert_options=>{}, 
:default_style=>:original, :default_url=>":style/missing.png", 
:escape_url=>true, :restricted_characters=>/[&$+,\/:;=?@<>\[\]\ 
{\}\|\\\^~%# ]/, :filename_cleaner=>nil, 
:hash_data=>":class/:attachment/:id/:style/:updated_at", 
:hash_digest=>"SHA1", :interpolator=>Paperclip::Interpolations, 
:only_process=>[], 
:path=>"/:class/:attachment/:id_partition/:style/:filename", 
:preserve_files=>false, :processors=>[:thumbnail], 
:source_file_options=>{:all=>"-auto-orient"}, :storage=>:s3, 
:styles=>{:large=>"500x500#", :medium=>"200x200#", 
:thumb=>"100x100#"}, :url=>":s3_path_url", 
:url_generator=>Paperclip::UrlGenerator, 
:use_default_time_zone=>true, :use_timestamp=>true, :whiny=>true, 
:validate_media_type=>true, :adapter_options=> 
{:hash_digest=>Digest::MD5}, 
:check_validity_before_processing=>true, :s3_host_name=>"s3-us- 
west-2.amazonaws.com", :s3_protocol=>"https", :s3_credentials=> 
{:bucket=>"example", :access_key_id=>"REDACTED", 
:secret_access_key=>"REDACTED", 
:s3_region=>"us-west-2"}}, @post_processing=true, 
@queued_for_delete=[], @queued_for_write={}, @errors={}, 
@dirty=false, @interpolator=Paperclip::Interpolations, 
@url_generator=#<Paperclip::UrlGenerator:0x000055b3e043a8e8 
@attachment=#<Paperclip::Attachment:0x000055b3e043aa50 ...>>, 
@source_file_options={:all=>"-auto-orient"}, @whiny=true, 
@s3_options={}, @s3_permissions={:default=>:"public-read"}, 
@s3_protocol="https", @s3_metadata={}, @s3_headers={}, 
@s3_storage_class={:default=>nil}, 
@s3_server_side_encryption=false, @http_proxy=nil, 
@use_accelerate_endpoint=nil>

user.avatar(:thumb)返回:

  

https://s3-us-west-2.amazonaws.com/example/users/avatars/000/000/001/thumb/two_people_talking.gif?1560705432

现在,我正在尝试允许用户通过react-native应用程序上传新的/更改的图像,而后端是Nodejs,这对我来说是相对较新的。

我很困惑如何实现这一点,尤其是因为这些示例都引用了我没有使用过的Mongoose。

仅显示如何成功更新用户,这是如何更新用户的first_name

users.updateUserPhoto = (req, res) => {

  let id = req.decoded.id
  let first_name = req.body.first_name

  models.Users.update(
      first_name: first_name,
      {
        where: {
          id: req.decoded.id
        }
      },
    ).then(response => {
        res.status(200).json({ status: 200, data: { response } });
    })
    .catch(error => {
        res.status(500).json({ status: 500, err: error });
    })
}

这是我找到的node-paperclip-s3包裹,这是我要做的事情:

'use strict'
let users = {};
const { Users } = require('../models');
let models = require("../models/index");

let Sequelize = require('sequelize');
let Paperclip = require('node-paperclip');
let Op = Sequelize.Op;
let sequelizeDB = require('../modules/Sequelize');

users.updateUserPhoto = (req, res) => {
  let id = req.decoded.id
  let avatar = req.body.avatar <- this is a file path

  models.Users.plugin(Paperclip.plugins, {
      avatar: {
        styles: [
          { original: true },
          { large:     { width: 500,  height: 500 } },
          { medium:    { width: 200, height: 200 } },
          { thumb:  { width: 100, height: 100 } }
        ],
        prefix:      '/users/{{attachment}}/{{id}}/{{filename}}',
        name_format: '{{style}}.{{extension}}',
        storage: 's3',
        s3: {
          bucket: process.env.S3_BUCKET_NAME,
          region: 'us-west-2',
          key: process.env.AWS_ACCESS_KEY_ID,
          secret: process.env.AWS_SECRET_ACCESS_KEY,
        }
      }
  })

  models.Users.update(
      avatar,
      {
        where: {
          id: req.decoded.id
        }
      },
    ).then(response => {
        res.status(200).json({ status: 200, data: { response } });
    })
    .catch(error => {
        res.status(500).json({ status: 500, err: error });
    })
}

我也尝试过这样的事情:

    models.Users.update(Paperclip.plugins, {
      avatar: {
        styles: [
          { original: true },
          { large:     { width: 500,  height: 500 } },
          { medium:    { width: 200, height: 200 } },
          { thumb:  { width: 100, height: 100 } }
        ],
        prefix:      '/users/{{attachment}}/{{id}}/{{filename}}',
        name_format: '{{style}}.{{extension}}',
        storage: 's3',
        s3: {
          bucket: process.env.S3_BUCKET_NAME,
          region: 'us-west-2',
          key: process.env.AWS_ACCESS_KEY_ID,
          secret: process.env.AWS_SECRET_ACCESS_KEY,
        }
      },
      {
        where: {
          id: req.decoded.id
        }
      },
    ).then(response => {
        res.status(200).json({ status: 200, data: { response } });
    })
    .catch(error => {
        res.status(500).json({ status: 500, err: error });
    })
  })

我尝试过:

let new_avatar = (Paperclip.plugins, {
      avatar: {
        styles: [
          { original: true },
          { large:     { width: 500,  height: 500 } },
          { medium:    { width: 200, height: 200 } },
          { thumb:  { width: 100, height: 100 } }
        ],
        prefix:      `/users/avatars/{{attachment}}/{{id}}/{{filename}}`,
        name_format: '{{style}}.{{extension}}',
        storage: 's3',
        s3: {
          bucket: process.env.S3_BUCKET_NAME,
          region: 'us-west-2',
          key: process.env.AWS_ACCESS_KEY_ID,
          secret: process.env.AWS_SECRET_ACCESS_KEY,
        }
      },
  })

  let data = {
    avatar: new_avatar
  }

  models.Users.update(
      data,
      {
        where: {
          id: req.decoded.id
        }
      },
    ).then(response => {
        res.status(200).json({ status: 200, data: { response } });
    })
    .catch(error => {
        res.status(500).json({ status: 500, err: error });
    })

从上面链接中的示例中,我不了解它是如何保存到S3的,或者它是如何以Rails gem创建该记录的相同方式来更新数据库的。任何帮助或指针表示赞赏!

请让我知道您可能需要其他哪些信息才能完成此过程。

1 个答案:

答案 0 :(得分:0)

以下代码适用于nodeJ。     我添加了一个API,用于将前端的图像保存到AWS S3。

我在代码中添加了注释,以便更好地理解。

let str = `"sIDHistory": [ "21 34 49234328 9" ]`;

let arr = str.match(/([0-9]+)/g).map(Number);
console.log(arr);

这是老派的非理想解决方案。请尝试一下,让我知道。