gpt4 book ai didi

reactjs - 'ControllerBase.File(byte[], string)' 是一种方法,在给定上下文 (CS0119) 中无效 - 在方法中

转载 作者:行者123 更新时间:2023-12-03 13:57:00 26 4
gpt4 key购买 nike

我正在尝试创建一个应用程序,用户可以在其中上传文本文件,并获取更改后的文本。

我使用 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);
}

}

}

但是控制台抛出错误,说“'ControllerBase.File(byte[], string)'是一种方法,在给定上下文中无效(CS0119)”

由于此错误,“'HomeController.UploadToBlob(string, object, Stream)': 并非所有代码路径都返回值 (CS0161)”之后又出现另一个错误

我的问题是

  1. 像我一样创建一个单独的方法是更好的主意吗?
  2. 如何解决有关"file"在 UploadToBlob 方法内有效的问题?
  3. 如果我想添加文件类型验证,应该在哪里进行?德克萨斯州仅文本文件有效
  4. 如果我想从上传的文本文件中读取文本字符串,我应该在哪里调用
  string contents = blob.DownloadTextAsync().Result;

return contents;
  • 如何将“内容”传递给我的 react 组件?像这样的吗?
  •     useEffect(() => {
    fetch('Home')
    .then(response => response.json())
    .then(data => {
    setForcasts(data)
    })
    }, [])

    感谢您帮助这位 super 新手使用 ASP.NET Core!

    最佳答案

    1) 可以将上传放入单独的方法中,也可以将其放入单独的类中来处理 blob 操作

    2) File 是 Controller 方法之一的名称,如果要从 System.IO 命名空间引用 File 类,则需要完全限定名称

    FileStream uploadFileStream = System.IO.File.OpenRead(localFilePath);

    对于另一个编译错误,您需要从 UploadToBlob 方法返回一些内容,现在它不会从 try block 返回任何内容

    3)文件类型验证可以放入 Controller 操作方法中

    4)这取决于您打算如何处理文本以及您将如何使用它。这会是 Controller 的新操作(新的 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;
    }
    }

    它将以这种方式在您的 Post 方法中使用:

    using (var stream = formFile.OpenReadStream())
    {
    var streamWithReplacement = FindMostFrequentWordAndReplaceIt(stream);

    // Upload the replaced text:
    (uploadSuccess, uploadedUri) = await UploadToBlob(formFile.FileName, null, streamWithReplacement);

    }

    关于reactjs - 'ControllerBase.File(byte[], string)' 是一种方法,在给定上下文 (CS0119) 中无效 - 在方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60927331/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com