2017-08-05 48 views
0

如何在运行时设置HttpPostedFileBase ContentType值?如何在运行时设置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 
    //============== 
+0

'HttpPostedFileBase'用于从浏览器上传文件。它的'ContentType'是只读的(它只能吸气)。什么是“MemoryPostedFile”?你想在这里做什么? –

+0

我想MemoryPostedFile到这个HttpPostedFileBase。有没有办法? –

+0

你还没有说过'MemoryPostedFile'是什么。但这样做没有意义。你想实现什么? –

回答

0

非常感谢@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; } 
    } 
相关问题