gpt4 book ai didi

c# - 无法将 HttpPostedFileBase 转换为字节 []

转载 作者:太空狗 更新时间:2023-10-29 22:22:21 25 4
gpt4 key购买 nike

我有一个接受 HttpPostedFileBase(.jpg 或 .png 等)的 Controller 。

public ActionResult SaveImage(HttpPostedFileBase ImageData)
{
//code
}

ImageData 成为具有以下属性的 System.Web.HttpPostedFileWrapper 对象:

ContentLength: 71945
ContentType: "image/png"
FileName: "foo.png"
InputStream: {System.Web.HttpInputStream}

我没有任何问题获取 ImageData 并将其转换为图像,然后将图像转换为 byte[],然后转换为 base64 字符串 - 但我尝试将其直接转换为 byte[]以下代码:

byte[] imgData;

using (Stream inputStream = ImageData.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}

imgData = memoryStream.ToArray();
}

memoryStream 在调用 imgData = memoryStream.ToArray(); 时始终为空,因此 imgData 最终也为空.

我很难理解为什么我无法将此 InputStream 读入 MemoryStream。 InputStream 似乎很好,除了 readTimeout 和 writeTimeout 属性抛出 timeouts are not supported on this stream。我做错了什么,为什么我不能将 ImageData 转换为 byte[]?

以防万一,这是我的 AJAX 调用。 contentTypeprocessData 选项设置为 false 是否有问题?

$.ajax({
url: 'SaveImage',
data: formData,
type: "POST",
contentType: false,
processData: false,
beforeSend: function () {
$("#loadingScreenModal").modal('toggle');
},
success: function (data) {
// etc.
}
});

更新:我通过将 HttpPostedFileBase 转换为 Image,然后转换 Image 解决了这个问题到 byte[],但我仍然想弄清楚为什么我必须执行这个中间步骤。

Image i = Image.FromStream(ImageData.InputStream, true, true);
byte[] imgData = imageToByteArray(thumb);

public byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}

更新 #2: 我认为我的代码的问题可能是 if (memoryStream == null) block 中的代码从未被调用.

最佳答案

您可以使用 BinaryReader 类将字符串读入字节数组:

byte[] imgData;

using (var reader = new BinaryReader(ImageData.InputStream))
{
imgData = reader.ReadBytes(ImageData.ContentLength);
}

关于c# - 无法将 HttpPostedFileBase 转换为字节 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com