【问题标题】:how set HttpPostedFileBase ContentType value in runtime如何在运行时设置 HttpPostedFileBase ContentType 值
【发布时间】:2018-01-13 03:29:54
【问题描述】:

如何在运行时设置 HttpPostedFileBase ContentType 值?

    HttpPostedFileBase upl=null;
    string path="/exelFile/book1.xlsx";

    //-----Set Name Runtime 
    var Name="FileName.xlsx";
    //-----Set Type Runtime 
    var type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";         
    byte[] bytes =System.IO.File.ReadAllBytes(Server.MapPath(Path));
    upl = (HttpPostedFileBase)new MemoryPostedFile(bytes, Name);

    //=====>how set type
    upl.ContentType 
    //==============

【问题讨论】:

  • HttpPostedFileBase 用于从浏览器上传文件。并且它的ContentType 是只读的(它只有吸气剂)。 MemoryPostedFile 是什么?你想在这里做什么?
  • 我正在尝试 MemoryPostedFile 到这个 HttpPostedFileBase。没有办法吗?
  • 你还没说MemoryPostedFile是什么。但这样做没有任何意义。你想达到什么目标?
  • 我在文件上传的具体情况下改变它的值
  • 不清楚你的意思,但它是read-only property

标签: c# asp.net-mvc runtime


【解决方案1】:

非常感谢@StephenMuecke。通过将'ContentType'添加到以下函数中即可解决。

  public class MemoryPostedFile : HttpPostedFileBase
    {
        private readonly byte[] fileBytes;

        public MemoryPostedFile(byte[] fileBytes, string fileName = null,string ContentType=null)
        {
            this.fileBytes = fileBytes;
            this.FileName = fileName;
            this.ContentType = ContentType;
            this.InputStream = new MemoryStream(fileBytes);
        }

        public override int ContentLength => fileBytes.Length;

        public override string FileName { get; }

        public override string ContentType { get; }

        public override Stream InputStream { get; }
    }

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    相关资源
    最近更新 更多