C# 如何使用c将字节[]转换为HttpPostedFileBase#
如何使用c#将字节[]转换为HttpPostedFileBase。在这里,我尝试了以下方法C# 如何使用c将字节[]转换为HttpPostedFileBase#,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,如何使用c#将字节[]转换为HttpPostedFileBase。在这里,我尝试了以下方法 byte[] bytes = System.IO.File.ReadAllBytes(localPath); HttpPostedFileBase objFile = (HttpPostedFileBase)bytes; 我收到无法隐式转换错误。创建自定义postedfile如何?:) 您可以这样简单地使用: byte[] bytes = System.IO.File.ReadAllBytes(loca
byte[] bytes = System.IO.File.ReadAllBytes(localPath);
HttpPostedFileBase objFile = (HttpPostedFileBase)bytes;
我收到无法隐式转换错误。创建自定义postedfile如何?:) 您可以这样简单地使用:
byte[] bytes = System.IO.File.ReadAllBytes(localPath);
HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(bytes);
行
私有流inputStream可能重复代码>不需要也不使用。我试图编辑答案,但我发现。@Oskar你完全正确(关于不必要的inputStream字段),我在写答案时完全忽略了这一点。我会相应地更新。感谢您指出这一点。我在下面一行编译时遇到以下错误:line:public override int ContentLength=>fileBytes.Length;错误:fileBytes是一个字段,但用作类型。请帮我解决这个问题@KarlPatrikJohansson@Ronak在我看来,您使用的是早期版本的C#,它不允许您使用arrow=>操作符定义get only(readonly)属性。您可以尝试替换public override int ContentLength=>fileBytes.Length
使用public override int ContentLength{get return fileBytes.Length;}
Hi@Zerratar,我使用了您的代码,可以将memorypostedfilebase分配给httppostedfilebase。但每当我试图将这个memorypostedfilebase保存到服务器时,就会出现一个错误,表明该方法或操作未实现。你能帮帮我吗?请解释一下为什么你的代码剪能解决这个问题。更多信息请点击此处:
byte[] bytes = System.IO.File.ReadAllBytes(localPath);
HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(bytes);
public class HttpPostedFileBaseCustom: HttpPostedFileBase
{
MemoryStream stream;
string contentType;
string fileName;
public HttpPostedFileBaseCustom(MemoryStream stream, string contentType, string fileName)
{
this.stream = stream;
this.contentType = contentType;
this.fileName = fileName;
}
public override int ContentLength
{
get { return (int)stream.Length; }
}
public override string ContentType
{
get { return contentType; }
}
public override string FileName
{
get { return fileName; }
}
public override Stream InputStream
{
get { return stream; }
}
}
byte[] bytes = System.IO.File.ReadAllBytes(localPath);
var contentTypeFile = "image/jpeg";
var fileName = "images.jpeg";
HttpPostedFileBase objFile = (HttpPostedFileBase)new
HttpPostedFileBaseCustom(new MemoryStream (bytes), contentTypeFile, fileName);