azure 将以西里尔文命名的文件上载到blob容器中

bkhjykvo  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(95)

在将.docx文件上传到blob容器时遇到了一个意想不到的问题。在我将文件上传到blob容器的那一行,我得到了一个System.AggregateException.通过反复试验,我发现这是对文件名中西里尔字母的React。我该如何修复它?
上传代码:

using Azure.Storage.Blobs;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Cors;
using Azure.Storage.Blobs.Models;
using System.IO;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace DocxSender.API.Controllers
{
    [ApiController]
    [Route("api/upload")]
    public class UploadController : Controller
    {
        private readonly IConfiguration _config;

        public UploadController(IConfiguration config)
        {
            _config = config;
        }

        [HttpPost]
        public async Task<IActionResult> Upload([FromForm] IFormFile file, [FromForm] string userEmail)
        {
            // Get Blob settings
            string containerConnectionString = _config.GetValue<string>("ConnectionString");
            string blobName = _config.GetValue<string>("BlobName");

            // Generate unique File Name for Blob
            string fileName = Guid.NewGuid().ToString();
            string extension = Path.GetExtension(file.FileName);

            BlobServiceClient blobServiceClient = new BlobServiceClient(containerConnectionString);
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(blobName);
            BlobClient blobClient = containerClient.GetBlobClient(fileName + extension);

            var metadata = new Dictionary<string, string>
            {
                { "Email", userEmail },
                { "UserFileName", file.FileName }
            };

            try
            {
                // Upload the stream to the blob with the metadata
                await blobClient.UploadAsync(file.OpenReadStream(), new BlobUploadOptions()
                {
                    Metadata = metadata
                });

                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Error uploading file: {ex.Message}");
            }
        }
    }
}

kyks70gy

kyks70gy1#

如果您阅读错误消息,您会注意到出现此错误的原因是其中一个元数据(UserFileName)值包含无效字符。
请求标头中包含的元数据名称/值只能包含ASCII字符。
解决此问题的一种可能方法是将UserFileName元数据值转换为Base64编码的字符串,然后将其保存为元数据。

相关问题