无法将 CSV 文件上传到 Blob 存储

问题描述 投票:0回答:0

在 ASP.NET Web api 项目中,我使用以下代码将文件上传到 Blob 存储。此代码适用于 XLS 文件,但对于 CSV 文件会出现问题。

我收到以下 CSV 错误:

using (var stream = file.OpenReadStream()) is giving me "cannot access a disposed object" error

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using System;
using System.IO;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class BlobController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> UploadFile(IFormFile file)
    {
        try
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("No file selected.");
            }
        // Retrieve the connection string from your configuration or secure storage.
        string connectionString = "your_connection_string_here";

        // Create a reference to the Blob storage client.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        // Get a reference to the container where you want to upload the file.
        CloudBlobContainer container = blobClient.GetContainerReference("your_container_name_here");

        // Create the container if it doesn't exist.
        await container.CreateIfNotExistsAsync();

        // Generate a unique name for the file to be uploaded.
        string fileName = Path.GetFileName(file.FileName);
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

        // Read the file content into a memory buffer.
        byte[] fileBytes;
        using (var memoryStream = new MemoryStream())
        {
            await file.CopyToAsync(memoryStream);
            fileBytes = memoryStream.ToArray();
        }

        // Upload the file to Azure Blob Storage using the memory buffer.
        await blockBlob.UploadFromByteArrayAsync(fileBytes, 0, fileBytes.Length);

        return Ok("File uploaded successfully.");
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"An error occurred: {ex.Message}");
    }
}

}

c# azure azure-blob-storage blob
© www.soinside.com 2019 - 2024. All rights reserved.