React Native 如何从www.example.com获取图片网址s3.amazonaws.com,PUT请求?

lztngnrs  于 2022-12-24  发布在  React
关注(0)|答案(1)|浏览(111)

我正在尝试处理上传到s3.amazonaws.com.
我写了两封回信:
1.从我的后端获取网址上传。
1.要把我的形象与'上传网址'从第一次回调s3。
但我无法从s3接收我上传的图像的URL。PUT请求后,我得到了一个空的响应。
我有这个代码:

// callback for getting upload url from my backend - works OK
const getPresignedUrl = useCallback(
  async (imageName: string) => {
    const configurationObject = {
      method: 'get',
      url: getUploadUrl(imageName, uploadImageCategory.AVATARS),
      headers: {
        Authorization: `Bearer ${token}`,
      },
    };
    const {data} = await axios(configurationObject);
    return data;
  },
  [getUploadUrl, token],
);

// function to get image body from uri - also OK
const getBlob = async (fileUri: string) => {
  const resp = await fetch(fileUri);
  const imageBody = await resp.blob();
  return imageBody;
};

// callback that puts my image to s3 server - seems like it's OK
const uploadUsingPresignedUrl = useCallback(
  async (preSignedUrl: string) => {
    const imageBody = await getBlob(uri);

    const configurationObject = {
      method: 'PUT',
      url: preSignedUrl,
      data: {
        body: imageBody,
      },
    };

    const {data} = await axios(configurationObject);
    return data;
  },
  [uri],
);

在下面的代码中,我调用这些函数:

const onUploadImage = useCallback(async () => {
  const imageName = getImageName(uri); //just util for getting right image name

  const presignedUrl = await getPresignedUrl(imageName);
  console.log('presignedUrl', presignedUrl); // I see generated URL in response

  const putImageOnAws = await uploadUsingPresignedUrl(presignedUrl);
  console.log('putImageOnAws', putImageOnAws); // Response is empty

}, [getImageName, getPresignedUrl, uploadUsingPresignedUrl, uri]);

useEffect(() => {
  if (uri) {
    setAvatar(uri);
    onUploadImage()
      .then()
      .catch(err => console.log('err: ', err));
  }
}, [onUploadImage, uri]);

所以当我调用putimageonaws时,我得到了空的响应。我认为应该有一个链接到我上传的图像...
所以我的问题是-我怎样才能得到我的图片上传到s3的网址?

lhcgjxsq

lhcgjxsq1#

上传后,文件的url中不会有你不拥有的特殊数据。当你请求预签名的url时,你已经指定了文件键(路径)和文件名。所以使用这些细节你可以自己构造文件url。这实际上取决于你的用例。如果你的s3 bucket是通过cloudfront发行版公开的,你的文件url看起来像这样,

https://<your-cloudfront-url>/<your-file-key-or-path>/<your-file-name-with-extension>

请为您的特定场景添加有关s3 bucket配置的更多详细信息。

相关问题