如何使用c#将byte[]转换为HttpPostedFileBase

本文关键字:转换 HttpPostedFileBase byte 何使用 | 更新日期: 2023-09-27 18:03:28

如何使用c#将byte[]转换为HttpPostedFileBase。在这里,我尝试了以下方法。

byte[] bytes = System.IO.File.ReadAllBytes(localPath);
HttpPostedFileBase objFile = (HttpPostedFileBase)bytes;

我得到一个不能隐式转换错误。

如何使用c#将byte[]转换为HttpPostedFileBase

如何创建自定义postdfile ?:)

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);