我正在创建一个应用程序,用户可以在其中上传他们的文本文件并了解其最常用的单词。
我试图按照这个文档来习惯使用 AZURE STORAGE BLOBS 的想法 - https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet
但我是超级新手,很难弄清楚如何为我的 POST 方法调整这些 blob 方法。
这是我的 sudo - 我认为我的控制器需要什么以及触发 POST 方法时需要发生什么。
a.无需DELETE或PUT,无需替换数据,也无需在此应用中删除
b.可能需要一个 GET 方法,但是一旦 POST 方法被触发,它应该将文本上下文传递给 FE 组件
POST 方法
- 与 Azure 存储帐户连接
- 如果是第一次 POST,则创建一个容器来存储文本文件 a. 如果已经制作了新容器,如何连接现有容器?我找到了这个,但这是为旧的 CloudBlobContainer 准备的。不是新的 SDK 12 版本。
.GetContainerReference($"{containerName}");
- 将文本文件上传到容器
- 获取所选文件的文本内容并返回
这是我的控制器。
public class HomeController : Controller
{
private IConfiguration _configuration;
public HomeController(IConfiguration Configuration)
{
_configuration = Configuration;
}
public IActionResult Index()
{
return View();
}
[HttpPost("UploadText")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
if (files != null)
{
try
{
string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
string containerName = "textdata" + Guid.NewGuid().ToString();
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
//Q. How to write a if condition here so if the POST method has already triggered and container already created, just upload the data. Do not create a new container?
string fileName = //Q. how to get the chosen file name and replace with newly assignmed name?
string localFilePath = //Q. how to get the local file path so I can pass on to the FileStream?
BlobClient blobClient = containerClient.GetBlobClient(fileName);
using FileStream uploadFileStream = System.IO.File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
string data = System.IO.File.ReadAllText(localFilePath, Encoding.UTF8);
//Q. If I use fetch('Home').then... from FE component, will it receive this data? in which form will it receive? JSON?
return Content(data);
}
catch
{
//Q. how to use storageExeption for the error messages
}
finally
{
//Q. what is suitable to execute in finally? return the Content(data) here?
if (files != null)
{
//files.Close();
}
}
}
//Q. what to pass on inside of the Ok() in this scenario?
return Ok();
}
}
Q1。如何检查 POST 方法是否已经被触发并创建了容器?如果是这样,我如何获取容器名称并连接到它?
Q2。我应该给所选文件一个新的分配名称吗?我该怎么做?
Q3。如何获取所选文件的名称,以便通过以处理 Q2?
Q4。如何获取本地文件路径以便我可以传递给 FileStream?
Q5。如何返回 Content 数据并传递给 FE?通过fetch('Home').then...这样使用?
Q6。如何将 storageExeption 用于错误消息
问题 7。最后适合执行什么?在这里返回内容(数据)?
Q8。在这种情况下,在 Ok() 内部传递什么?
欢迎任何帮助!我知道我在这里问了很多问题。非常感谢!