yoo*_*vak 9 azure azure-storage-blobs reactjs asp.net-core
我正在尝试创建一个应用程序,用户可以在其中上传文本文件,并取回更改后的文本。
我使用 React 作为 FE 和 ASP.NET Core 用于 BE 和 Azure 存储作为数据库存储。
这就是我的 HomeController 的样子。我创建了一个单独的“UploadToBlob”方法来发布数据
public class HomeController : Controller
{
private readonly IConfiguration _configuration;
public HomeController(IConfiguration Configuration)
{
_configuration = Configuration;
}
public IActionResult Index()
{
return View();
}
[HttpPost("UploadFiles")]
//OPTION B: Uncomment to set a specified upload file limit
[RequestSizeLimit(40000000)]
public async Task<IActionResult> Post(List<IFormFile> files)
{
var uploadSuccess = false;
string uploadedUri = null;
foreach (var formFile in files)
{
if (formFile.Length <= 0)
{
continue;
}
// read directly from stream for blob upload
using (var stream = formFile.OpenReadStream())
{
// Open the file and upload its data
(uploadSuccess, uploadedUri) = await UploadToBlob(formFile.FileName, null, stream);
}
}
if (uploadSuccess)
{
//return the data to the view, which is react display text component.
return View("DisplayText");
}
else
{
//create an error component to show there was some error while uploading
return View("UploadError");
}
}
private async Task<(bool uploadSuccess, string uploadedUri)> UploadToBlob(string fileName, object p, Stream stream)
{
if (stream is null)
{
try
{
string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
//Create a unique name for the container
string containerName = "textdata" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
string localPath = "./data/";
string textFileName = "textdata" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, textFileName);
// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(textFileName);
Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
FileStream uploadFileStream = File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
}
catch (StorageException)
{
return (false, null);
}
finally
{
// Clean up resources, e.g. blob container
//if (blobClient != null)
//{
// await blobClient.DeleteIfExistsAsync();
//}
}
}
else
{
return (false, null);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是控制台抛出错误,说“'ControllerBase.File(byte[], string)'是一种方法,在给定的上下文中无效(CS0119)”
由于这个错误,另一个错误出现在“'HomeController.UploadToBlob(string, object, Stream)': not all code paths return a value (CS0161)”
我的问题是
string contents = blob.DownloadTextAsync().Result;
return contents;
Run Code Online (Sandbox Code Playgroud)
useEffect(() => {
fetch('Home')
.then(response => response.json())
.then(data => {
setForcasts(data)
})
}, [])
Run Code Online (Sandbox Code Playgroud)
感谢您使用 ASP.NET Core 帮助这个超级新手!
Mar*_*cik 13
1) 可以把上传放到单独的方法中,也可以放到单独的类中处理blob操作
2)File是控制器方法之一的名称,如果File要从 System.IO 命名空间引用该类,则需要完全限定名称
FileStream uploadFileStream = System.IO.File.OpenRead(localFilePath);
Run Code Online (Sandbox Code Playgroud)
对于另一个编译错误,您需要从UploadToBlob方法中返回一些内容,现在它不会从try块中返回任何内容
3)文件类型验证可以放入控制器动作方法中
4)这取决于您打算对文本做什么以及您将如何使用它。它会是控制器的新动作(新的 API 端点)吗?
5) 您可以创建一个新的 API 端点来下载文件
更新:
对于单词替换,您可以使用类似的方法:
private Stream FindMostFrequentWordAndReplaceIt(Stream inputStream)
{
using (var sr = new StreamReader(inputStream, Encoding.UTF8)) // what is the encoding of the text?
{
var allText = sr.ReadToEnd(); // read all text into memory
// TODO: Find most frequent word in allText
// replace the word allText.Replace(oldValue, newValue, stringComparison)
var resultText = allText.Replace(...);
var result = new MemoryStream();
using (var sw = new StreamWriter(result))
{
sw.Write(resultText);
}
result.Position = 0;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
它将以这种方式在您的 Post 方法中使用:
using (var stream = formFile.OpenReadStream())
{
var streamWithReplacement = FindMostFrequentWordAndReplaceIt(stream);
// Upload the replaced text:
(uploadSuccess, uploadedUri) = await UploadToBlob(formFile.FileName, null, streamWithReplacement);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6609 次 |
| 最近记录: |