简体   繁体   English

将图像上传到 s3 存储桶 - 反应本机和 node.js

[英]Upload image to s3 bucket - react native and node js

Within my app a user can select a profile image and i would like that image to be uploaded to an s3 bucket when the user saves their profile data在我的应用程序中,用户可以 select 个人资料图片,我希望在用户保存个人资料数据时将该图片上传到 s3 存储桶

I pass the image data (and json, which consists of name, email, telephone for example) from my app to an express server and upload there我将图像数据(和 json,例如姓名,email,电话)从我的应用程序传递到快速服务器并上传到那里

At present I can pass the image data (the url it seems at present) to an s3 bucket and it saves目前我可以将图像数据(目前看来是 url)传递到 s3 存储桶并保存

I don't think i'm actually saving the image itself though, as when downloading from s3 (manually) and trying to open on my mac it states it may be damaged and i cannot see the image我不认为我实际上是在保存图像本身,因为当从 s3(手动)下载并尝试在我的 mac 上打开时,它表明它可能已损坏并且我看不到图像

Feel daft for asking but how do i actually upload the image itself?感觉很愚蠢,但我实际上如何上传图像本身? Thanks谢谢

React Native Side反应本机端

const handleFormSubmit = formData => {
  const jsonData = JSON.stringify({
    ...formData,
  });

  // Handle profile image
  if (imageProps && imageProps.uri) {
    const data = new FormData();
    data.append('formBody', jsonData);
    data.append('image', {
      uri:
        Platform.OS === 'android'
        ? imageProps.uri
        : imageProps.uri.replace('file://', ''),
      type: imageProps.type,
      name: imageProps.fileName,
    });
    sendRequest(data);
  } else {
    sendRequest(jsonData);
  }
};

 const sendRequest = data => {
   let responseData;
   fetch('http://localhost:8080/users/api/update_user_profile', {
     method: 'POST',
     headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: data,
  })
  .then(response => {
    responseData = response;
    return response.json();
  })
  .then(jsonData => {
    console.log(jsonData)
  })
  .catch(error => {
    console.log(error)
  });
};

Server Side服务器端

const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});

// Setting up S3 upload parameters
  const params = {
    Bucket: 'bucket-folder',
    ACL: 'public-read',
    Key: req.files.image.name,
    Body: req.files.image.path
  };

const stored = await s3.upload(params).promise();

You can use Multer for uploading files to s3.您可以使用 Multer 将文件上传到 s3。

const multer = require('multer');
const AWS = require('aws-sdk');
const uniqid = require('uniqid');
const storage = multer.memoryStorage();
const upload = multer({ storage });


// ? Posts new file to amazon and saves to db
router.post(
    '/:id',
    upload.single('attachment'),
    async (req, res) => {
        const unique = uniqid.time();
        const { file } = req;
        const { filePath } = req.body;
        const { id } = req.params;
        const s3FileURL = process.env.AWS_UPLOADED_FILE_URL;
        const region = process.env.AWS_REGION;
        const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
        const accessKeyId = process.env.AWS_ACCESS_KEY_ID;
        const Bucket = process.env.AWS_BUCKET_NAME + '/' + filePath;
        const Key = `${id}/${unique}-${file.originalname}`;
        const Body = file.buffer;
        const ContentType = file.mimetype;
        const ACL = 'public-read';

        const s3bucket = new AWS.S3({
            accessKeyId,
            secretAccessKey,
            region,
        });

        const params = {
            Bucket,
            Key,
            Body,
            ContentType,
            ACL,
        };

        s3bucket.upload(params, async (err, data) => {
            if (err) {
                res.status(500).json({ error: true, Message: err });
            } else {
                console.log(params);
                const newFileUploaded = {
                    description: req.body.description,
                    fileLink: `${s3FileURL}${filePath}/${id}/${unique}-${file.originalname}`,
                    s3_key: params.Key,
                };
                try {
                    const response = await postFile({
                        name: req.body.name,
                        attachment: newFileUploaded,
                        alt: req.body.alt,
                        user: req.body.user,
                        relatedID: req.body.relatedID,
                    });

                    res.status(200).json({
                        message: response.message,
                        success: response.success,
                        result: response.result,
                    });
                } catch (e) {
                    res.status(500).json({
                        message:
                            'File upoladed but Db couldnt saved request (upload  by ID)',
                        success: false,
                        result: [],
                    });
                }
            }
        });
    }
);

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

相关问题 如何使用 React js 将图像上传到 Amazon S3 存储桶? - How to upload image to an Amazon S3 bucket using React js? 从 opencv 上传图片到 s3 bucket - Upload image from opencv to s3 bucket React-native 上传图片到亚马逊s3 - React-native upload image to amazons s3 直接下载存储在S3 bucket中的文件到React客户端,而不是通过Node.js服务器 - Download file stored in S3 bucket directly to React client, instead of passing through Node.js server 将大于 1MB 的文件上传到 S3 Bucket (Node.js) 时出现错误代码 500 - Get the error code 500 when I upload a file size > 1MB to S3 Bucket (Node.js) 如何从 React 前端将文件上传到 AWS S3 存储桶 - How to upload files to AWS S3 bucket from the react frontend 如何将图像文件从 s3 存储桶上传到 cloudinary (nodejs) - How to upload an image file from an s3 bucket to cloudinary (nodejs) 如何在 laravel 5.5 的 s3 存储桶中上传图像 - How to upload image in s3 bucket in laravel 5.5 使用 Api Gateway、Lambda 函数将图像上传到 S3 存储桶 - Upload Image into S3 bucket using Api Gateway, Lambda funnction 我们如何使用 node.js 将 m3u8 文件和相应的 ts 文件上传到 amazon s3 存储桶 - How can we upload m3u8 file and corresponding ts file to amazon s3 bucket using node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM