【问题标题】:how to convert a byte[] to HttpPostedFileBase using c#如何使用 c# 将 byte[] 转换为 HttpPostedFileBase
【发布时间】:2019-03-15 20:10:19
【问题描述】:

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

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

我得到一个无法隐式转换的错误。

【问题讨论】:

标签: c# asp.net-mvc-4


【解决方案1】:

创建自定义发布文件怎么样? :)

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

【讨论】:

  • private Stream inputStream; 不需要也未使用。我试图编辑答案,但我发现we are not supposed to edit each others code.
  • @Oskar 你是完全正确的(关于不必要的 inputStream 字段)当我写答案时我完全错过了。我会相应地更新。感谢您指出这一点。
  • 在下面的行中编译时出现以下错误: Line: public override int ContentLength => fileBytes.Length;错误:fileBytes 是一个字段,但用作类型。请帮我解决@KarlPatrikJohansson
  • @Ronak 在我看来,您使用的是早期版本的 C#,它不允许您使用箭头 => 运算符定义 get-only(只读)属性。您可以尝试将public override int ContentLength => fileBytes.Length; 替换为public override int ContentLength { get return fileBytes.Length; }
  • 嗨@Zerratar,我使用了你的代码,我可以将memorypostedfilebase分配给httppostedfilebase。但是,每当我尝试将此 memorypostedfilebase 保存到服务器时,我都会收到错误消息,指出方法或操作未实现。你能帮帮我吗?
【解决方案2】:
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);

【讨论】:

  • 请提供一些解释,说明您的代码片段为何能解决问题。更多信息:How to Answer
猜你喜欢
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
相关资源
最近更新 更多