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

2024-02-28

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

我使用 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)': not all code paths return a value (CS0161)”之后

我的问题是

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

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

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


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

2) File是控制器方法之一的名称,如果您想引用File来自 System.IO 命名空间的类,您需要完全限定该名称

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

对于其他编译错误,您需要从UploadToBlob方法,现在它不会从try block

3)文件类型验证可以放入控制器的action方法中

4)这取决于你打算如何处理文本以及你将如何使用它。这会是控制器的新操作(新的 API 端点)吗?

5) 您可以创建一个新的 API 端点来下载文件

UPDATE:

对于单词替换,您可以使用类似的方法:

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);

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐