繁体   English   中英

使用ASP.NET Web API将图像添加到Azure blob存储失败

[英]Adding an image to Azure blob storage using ASP.NET Web API fails

我有一个Azure blob容器用于存储图像。 我还有一套ASP.NET Web API方法,用于在此容器中添加/删除/列出blob。 如果我将图像作为文件上传,这一切都有效。 但是我现在想要将图像作为流上传并且收到错误。

public async Task<HttpResponseMessage> AddImageStream(Stream filestream, string filename)
    {
        try
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            BlobStorageService service = new BlobStorageService();
            await service.UploadFileStream(filestream, filename, "image/png");
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }
        catch (Exception ex)
        {
            base.LogException(ex);
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
        }

将新图像作为流添加到blob容器的代码如下所示。

public async Task UploadFileStream(Stream filestream, string filename, string contentType)
    {
        CloudBlockBlob blockBlobImage = this._container.GetBlockBlobReference(filename);
        blockBlobImage.Properties.ContentType = contentType;
        blockBlobImage.Metadata.Add("DateCreated", DateTime.UtcNow.ToLongDateString());
        blockBlobImage.Metadata.Add("TimeCreated", DateTime.UtcNow.ToLongTimeString());
        await blockBlobImage.UploadFromStreamAsync(filestream);
    }

最后这是我的单元测试失败了。

[TestMethod]
    public async Task DeployedImageStreamTests()
    {
        string blobname = Guid.NewGuid().ToString();

        //Arrange
        MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes($"This is a blob called {blobname}."))
        {
            Position = 0
        };

        string url = $"http://mywebapi/api/imagesstream?filestream={stream}&filename={blobname}";
        Console.WriteLine($"DeployedImagesTests URL {url}");
        HttpContent content = new StringContent(blobname, Encoding.UTF8, "application/json");
        var response = await ImagesControllerPostDeploymentTests.PostData(url, content);

        //Assert
        Assert.IsNotNull(response);
        Assert.IsTrue(response.IsSuccessStatusCode); //fails here!!
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }

我得到的错误是值不能为空。 参数名称:source

这是使用Web API将图像流上传到Azure blob存储的正确方法吗? 我有它没有问题的图像文件,现在只有我尝试使用流上传时才遇到此问题。

这是使用Web API将图像流上传到Azure blob存储的正确方法吗? 我有它没有问题的图像文件,现在只有我尝试使用流上传时才遇到此问题。

根据您的描述和错误消息,我发现您将您的网址中的流数据发送到网络API。

根据这篇文章:

Web API使用以下规则绑定参数:

如果参数是“简单”类型,则Web API会尝试从URI获取值。 简单类型包括.NET基元类型(int,bool,double等),以及TimeSpan,DateTime,Guid,decimal和string,以及具有可以从字符串转换的类型转换器的任何类型。 (稍后将详细介绍类型转换器。)

对于复杂类型,Web API尝试使用媒体类型格式化程序从邮件正文中读取值。

在我看来,流是一个复杂的类型,所以我建议你可以将它作为主体发布到web api。

此外,我建议您可以创建一个文件类,并使用Newtonsoft.Json将其转换为json作为消息的内容。

更多细节,您可以参考以下代码。 文件类:

  public class file
    {
        //Since JsonConvert.SerializeObject couldn't serialize the stream object I used byte[] instead
        public byte[] str { get; set; }
        public string filename { get; set; }

        public string contentType { get; set; }
    }

Web Api:

  [Route("api/serious/updtTM")]
    [HttpPost]
    public void updtTM([FromBody]file imagefile)
    {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("aaaaa");
            var client = storageAccount.CreateCloudBlobClient();
            var container = client.GetContainerReference("images");

            CloudBlockBlob blockBlobImage = container.GetBlockBlobReference(imagefile.filename);
            blockBlobImage.Properties.ContentType = imagefile.contentType;
            blockBlobImage.Metadata.Add("DateCreated", DateTime.UtcNow.ToLongDateString());
            blockBlobImage.Metadata.Add("TimeCreated", DateTime.UtcNow.ToLongTimeString());

            MemoryStream stream = new MemoryStream(imagefile.str)
            {
                Position=0
            };
            blockBlobImage.UploadFromStreamAsync(stream);
        }

测试控制台:

 using (var client = new HttpClient())
            {
                string URI = string.Format("http://localhost:14456/api/serious/updtTM");
                file f1 = new file();

                byte[] aa = File.ReadAllBytes(@"D:\Capture2.PNG");

                f1.str = aa;
                f1.filename = "Capture2";
                f1.contentType = "PNG";
                var serializedProduct = JsonConvert.SerializeObject(f1); 
                var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
                var result = client.PostAsync(URI, content).Result;
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM