[英]how to convert a byte[] to HttpPostedFileBase using c#
如何使用c#將byte []轉換為HttpPostedFileBase。 在這里,我嘗試了以下方式。
byte[] bytes = System.IO.File.ReadAllBytes(localPath);
HttpPostedFileBase objFile = (HttpPostedFileBase)bytes;
我得到一個不能隱式轉換錯誤。
如何創建自定義的發布文件? :)
public class MemoryPostedFile : HttpPostedFileBase
{
private readonly byte[] fileBytes;
public MemoryPostedFile(byte[] fileBytes, string fileName = null)
{
this.fileBytes = fileBytes;
this.FileName = fileName;
this.InputStream = new MemoryStream(fileBytes);
}
public override int ContentLength => fileBytes.Length;
public override string FileName { get; }
public override Stream InputStream { get; }
}
你可以這樣使用:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.