转换HttpPostedFileBase为byte [] [英] Convert HttpPostedFileBase to byte[]
问题描述
在我的MVC应用程序中,我使用以下code上传文件。
MODEL
公共HttpPostedFileBase文件{搞定;组; }
查看
@ Html.TextBoxFor(M = GT; m.File,新的{type =文件})
一切工作正常。但我想结果FIEL转换为byte []我。如何能做到这一点。
控制器
公众的ActionResult ManagePhotos(ManagePhotos模型)
{
如果(ModelState.IsValid)
{
字节[] =图像model.File; //它不工作。如何可以将其转换为字节数组
}
}
由于达林说,可以从输入流中读取 - 但我会避免依赖单一全力以赴数据是可用的。如果您在使用.NET 4,这是简单的:
MemoryStream的目标=新的MemoryStream();
model.File.InputStream.CopyTo(目标);
字节[]数据= target.ToArray();
这是很容易,如果你想要写 CopyTo从
相当于在.NET 3.5。最重要的部分是您从<读href=\"http://msdn.microsoft.com/en-us/library/system.web.httppostedfilebase.inputstream.aspx\"><$c$c>HttpPostedFileBase.InputStream$c$c>.
有关高效的目的,您的可能的检查返回的流是否已经是的MemoryStream
:
字节[]数据;
使用(流的InputStream = model.File.InputStream)
{
的MemoryStream MemoryStream的=的InputStream为MemoryStream的;
如果(MemoryStream的== NULL)
{
MemoryStream的=新的MemoryStream();
inputStream.CopyTo(MemoryStream的);
}
数据= memoryStream.ToArray();
}
In my MVC application, I am using following code to upload a file.
MODEL
public HttpPostedFileBase File { get; set; }
VIEW
@Html.TextBoxFor(m => m.File, new { type = "file" })
Everything working fine .. But I am trying to convert the result fiel to byte[] .How can i do this
CONTROLLER
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = model.File; //Its not working .How can convert this to byte array
}
}
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
这篇关于转换HttpPostedFileBase为byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!