如何解决如何使用 webapi 从 Azure Blob 存储上传和下载任何文件?
所以我正在处理的 ASP.NET 中有一个 webapi,要求是从基于 React 构建的 webapp 接受图像(通常是文件),并根据请求返回文件。使用的存储服务是 Azure Blob 存储。 我是这个环境的新手,我发现都是关于如何通过控制台或直接应用程序而不是通过 api 上传文件的教程。我需要知道通过 React 应用程序发送什么,以便我的 webapi 可以接受并将其上传到 Blob 存储,以及通过我的 api 向 webapp 发送什么,以及示例代码。
解决方法
您需要将 Azure Storage NuGet 包添加到您的项目中,然后使用包中的内置类将您的文件上传到 Azure Blob 存储。
,关于这个问题,您可以将您的图像文件作为表单数据发送到您的 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;
- 服务器
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();
});
}
- 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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。