如何使用 NextJS API 将图像上传到 Azure Blob 存储?

问题描述 投票:0回答:2

我有一个 React 组件,它将用户的个人资料图像发送到代理 nextjs api(希望保留代理 API,以便 Azure 机密在浏览器网络选项卡中不可见)。

这是前端React代码:

 const [image, setImage] = useState({ preview: '', raw: '' })

  const handleImageChange = (e) => {
    setImage({
      preview: URL.createObjectURL(e.target.files[0]),
      raw: e.target.files[0]
    })
  }

     // Form the request for sending picture to server.
     const picFile = new FormData()
     picFile.append("image", image.raw)
     const picOptions = {
      method: 'POST',
      headers: {
        'Content-type': 'multipart/form-data'
      },
      body: picFile,
    }

const picResponse = await fetch(profilePicEndpoint, picOptions)
return (
<input accept=".png, .jpg, .jpeg" type="file" id="image-upload" style={{ display: 'none' }} onChange={handleImageChange} />
)

这是代理 (NextJS) api 通过 SAS 令牌发送到 Azure Blob 存储的内容

export default async function handler(req, res) {
    const body = req.body
    //handle sending profile pic to azure blob storage
    const blobEndpoint = 'https://STORAGEACCOUNT.blob.core.windows.net/MyContainerhere/Testfile.png?BunchofCredentialsHere'
    const blobOptions = {
      method: 'PUT',
      headers: {
        'x-ms-blob-type': 'BlockBlob'
      },
      body: req.body,
    }
    const blobResponse = await fetch(blobEndpoint, blobOptions)
    // console.log(blobResponse)

    // Sends a HTTP success code
    res.status(200).json({ message: ` Submission successful. Please give 24 hours for updates to be reflected on this page.` })
  }

它最终将 png 转换为一堆随机字符(我假设这是文件的二进制代码?)到 nextjs api,最终将相同的内容发送到 azure blob 存储。我只想将文件上传到 nextjs api,然后以 png/jpeg/任何图像类型上传到 azure blob 存储。

感谢您的任何帮助/想法。

azure next.js azure-blob-storage blob image-upload
2个回答
1
投票

我尝试使用下面的 next.js 代码将图像作为 blob 上传到我的存储帐户。

代码:

upload.js:

import { BlobServiceClient } from '@azure/storage-blob';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    try {
      const { base64Image } = req.body;

      const storageAccount = '<account-name>';
      const containerName = 'container-name>';
      const accessKey = '<access-key>';
      const connectionString = `<connect-string>`;

      const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);
      const containerClient = blobServiceClient.getContainerClient(containerName);
      const filename = `${Date.now()}.png`;
      const imageBuffer = Buffer.from(base64Image, 'base64');
      const blockBlobClient = containerClient.getBlockBlobClient(filename);
      await blockBlobClient.uploadData(imageBuffer, { blobHTTPHeaders: { blobContentType: 'image/png' } });

      res.status(200).json({ message: 'Image uploaded successfully' });
    } catch (error) {
      res.status(500).json({ error: 'Error occured' });
    }
  } else {
    res.status(405).json({ error: 'not allowed' });
  }
}

ImageUploader.js:

import { useState } from 'react';
import axios from 'axios';

export default function ImageUploader() {
  const [selectedImage, setSelectedImage] = useState(null);

  const handleImageUpload = async () => {
    if (selectedImage) {
      try {
        const reader = new FileReader();
        reader.readAsDataURL(selectedImage);
        reader.onloadend = async () => {
          const base64Image = reader.result.split(',')[1];

          await axios.post('/api/upload', { base64Image });
        };
      } catch (error) {
      }
    }
  };

  const handleImageChange = (event) => {
    const file = event.target.files[0];
    setSelectedImage(file);
  };

  return (
    <div>
      <input type="file" accept="image/*" onChange={handleImageChange} />
      <button onClick={handleImageUpload}>Upload Image to storage account</button>
    </div>
  );
}

index.js:

import ImageUploader from '../components/ImageUploader';  
  
export default function Home() {  
return (  
<div>   
<h1>Image Upload using Next-js</h1>  
<ImageUploader />  
</div>  
);  
}

我的项目结构如下所示,

enter image description here

输出:

运行成功如下,

enter image description here

使用上面的URL,我在浏览器中得到的输出如下,

enter image description here

选择图像文件并单击上传图像按钮,如下所示,

enter image description here

然后,图片成功上传到存储帐户,如下,

enter image description here


-1
投票

您好,我不断收到 404 错误,我认为这是因为名称可能错误,但我确保我正确复制了它们。那么,您使用容器名称还是其 sas 作为容器名称,是否可以在没有容器的情况下执行相同的操作?

© www.soinside.com 2019 - 2024. All rights reserved.