简体   繁体   English

上传 react-native 张图片到 S3

[英]Uploading react-native images to S3

I want to upload image from React-Native(expo) to Nodejs server as an image then post to S3.我想将图像作为图像从 React-Native(expo) 上传到 Nodejs 服务器,然后发布到 S3。

FRONTEND前端

  const [image, setImage] = useState(null);
  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
    if (!result.canceled) {
      console.log(result)
      setImage(result.assets[0].uri);
    }
  }; 


  if (image){
    try {
      const formdata = new FormData()
      formdata.append('name', 'avatar');
      formdata.append('fileData', {
      uri : image,
      type: 'image',
     });
      let res =  fetch('http://172.20.10.2:4000/upload', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        body: formdata,
      });
    
    } catch (e) {
      console.error(e);
    }

BACKEND后端

async function uploadFile(file) {
 
  const params = {
    Bucket:"XXX", // bucket you want to upload to
    Key: "filename",
    Body: file.data,
    ACL: "public-read",
  };
  const data = await client.upload(params).promise();
  return data.Location; // returns the url location
}

app.post("/upload", async (req, res) => {
  console.log(req.body.fileData)

//   const u = ????
//   const fileLocation = await uploadFile(u);
// console.log("-------------------------------")
//   return res.status(200).json({ location: fileLocation });
});

I am getting the filedata on the backend as some weird symbols.我将后端的文件数据作为一些奇怪的符号获取。 How would i use that data and be able to upload it as a file?我将如何使用该数据并将其作为文件上传? Thanks谢谢

I cannot upload data我无法上传数据

A better solution would be to use S3 presigned urls .更好的解决方案是使用S3 预签名 url You could request for a presigned url using lambda or through your nodejs server.您可以使用 lambda 或通过您的 nodejs 服务器请求预签名的 url。 To upload the file, you could do a http multipart upload on the returned url.要上传文件,您可以对返回的 url 进行 http 分段上传。

Here is how you could get a presigned url:以下是获得预签名 url 的方法:

  // Get signed URL from S3
  const s3Params = {
    Bucket: "bucketName",
    "bucketpath/image.jpg",
    Expires: 300, // Defines when the url expires in seconds
    ContentType: "image/jpeg",
  }

  const uploadURL = await s3.getSignedUrlPromise('putObject', s3Params)

This article might also be able to help you implement presigned urls. 本文或许还能帮助您实现预签名 url。

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

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