如何使用 webapi 从 Azure Blob 存储上传和下载任何文件?

问题描述

所以我正在处理的 ASP.NET 中有一个 webapi,要求是从基于 React 构建的 webapp 接受图像(通常是文件),并根据请求返回文件。使用的存储服务是 Azure Blob 存储。 我是这个环境的新手,我发现都是关于如何通过控制台或直接应用程序而不是通过 api 上传文件的教程。我需要知道通过 React 应用程序发送什么,以便我的 webapi 可以接受并将其上传到 Blob 存储,以及通过我的 api 向 webapp 发送什么,以及示例代码

解决方法

您需要将 Azure Storage NuGet 包添加到您的项目中,然后使用包中的内置类将您的文件上传到 Azure Blob 存储。

您可以在相同的 herehere 上找到一个基

,

关于这个问题,您可以将您的图像文件作为表单数据发送到您的 API。详情请参考以下步骤

  • 客户
import logo from "./logo.svg";
import "./App.css";
import React,{ useState } from "react";
import axios from "axios";

function App() {
  const [selectedFile,setSelectedFile] = useState();
  const [isFilePicked,setIsFilePicked] = useState(false);

  const changeHandler = (event) => {
    setSelectedFile(event.target.files[0]);
    setIsFilePicked(true);
  };

  const onFileUpload = async () => {
    const formData = new FormData();
    formData.append("file",selectedFile);
    formData.append("fileName",selectedFile.name);
    try {
      const res = await axios.post(
        "https://localhost:44349/weatherforecast",formData
      );
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div>
      <input type="file" name="file" onChange={changeHandler} />
      {isFilePicked ? (
        <div>
          <p>Filename: {selectedFile.name}</p>
          <p>Filetype: {selectedFile.type}</p>
          <p>Size in bytes: {selectedFile.size}</p>
        </div>
      ) : (
        <p>Select a file to show details</p>
      )}
      <div>
        <button onClick={onFileUpload}>Upload</button>
      </div>
    </div>
  );
}

export default App;

  • 服务器
  1. Configure CORS
public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder => builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod());
            });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors();
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
  1. API
[Consumes("multipart/form-data")]
        [HttpPost]
        public async Task<IActionResult> OnPostUploadAsync([FromForm] FileModel model)
        {
            try {

                string connectionString = "";
                BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
                var sourceContainer = blobServiceClient.GetBlobContainerClient("output");
                var blob = sourceContainer.GetBlockBlobClient(model.file.FileName);

                await blob.UploadAsync(model.file.OpenReadStream(),new BlobUploadOptions()
                {
                    HttpHeaders = new BlobHttpHeaders() { 
                      ContentType= model.file.ContentType
                    }
                });
                // Process uploaded files
                // Don't rely on or trust the FileName property without validation.

                return StatusCode(StatusCodes.Status201Created); ;

            } catch (Exception) {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
           
        }

enter image description here