0

我正在尝试从我的 .net 核心 API 中的多部分表单/数据中获取图像,但我无法弄清楚正在使用什么编码来加密这些图像数据。基本上我需要得到这个字符串中表示的字节数组(图像的)

但图像不渲染。读取身体值时我得到的尝试

这就是我得到这个编码字符串的方式:

 using (Stream responseStream = resposta.GetResponseStream())
 {
  var contentType = MediaTypeHeaderValue.Parse(response.ContentType);
  var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary).Value;

   for (MultipartReader smth = new(boundary, responseStream); ;)
   {
     try
     {
        MultipartSection section = await smth.ReadNextSectionAsync();

        if (section == null)
        break;

        string contentTypeFrame = section.ContentType;

        
        // Returns me the encoded string
        string bodyValue = await section.ReadAsStringAsync(); 
        if (bodyValue.ToLower().Contains("heartbeat"))
          continue;

       if (contentTypeFrame == "image/jpeg")
       {
         //Do something if it is an image
       }
    }

   catch (Exception ex) { }
  }
}

关于如何尝试解码此字符串以获取图像字节的任何想法?

4

1 回答 1

0

我想到了。

经过多次尝试,我得到了正确的代码来处理从“multipart/x-mixed-replace”获取文件;请求,一旦您将其分解为此处的 MultiPart 部分:

using (var httpResponse = (HttpWebResponse)request.GetResponse())
                using (Stream responseStream = httpResponse.GetResponseStream())
                {
                    MediaTypeHeaderValue contentType = MediaTypeHeaderValue
                        .Parse(request.ContentType);

                    string boundary = HeaderUtilities
                        .RemoveQuotes(contentType.Boundary).Value;

                    MultipartSection section;

                    for (MultipartReader smth = new(boundary, responseStream); ;)
                    {
                        section = await smth.ReadNextSectionAsync();

                        if (section is null) break;

                        var bytes = ConverteStreamToByteArray(section.Body);
                        
                        // Save or handle the Byte array
                    }
                }

OBS:如果你真的在寻找内容的字节,在任何情况下都不要使用 readasstringasync() 函数,它会改变内容的主体。(如果是图像,它会将内容类型和内容长度添加到正文中,您将无法再次将其转换为 jpg)

您现在只需要我编写的这个函数来从 Section Body Stream 中获取数据

 public static byte[] ConvertStreamToByteArray(Stream stream)
        {
            stream.Position = 0; 
            // for some reason the position aways starts at the last index, So make  
            // sure to set it to 0 here

            byte[] byteArray = new byte[16 * 1024];
            using (MemoryStream mStream = new())
            {
                int bit;
                while ((bit = stream.Read(byteArray, 0, byteArray.Length)) > 0)
                {
                    mStream.Write(byteArray, 0, bit);
                }
                return mStream.ToArray();
            }
        }
于 2021-08-25T21:55:19.507 回答