2017-02-16 52 views
3

我有一個ASP.NET核心應用程序,我需要驗證上傳的文件是圖像,而不是非圖像文件,它有一個圖像擴展名.... 我發現的所有解決方案都適用於System.Drawing.Image或類似的類,它們在ASP.NET Core中不可用。 你能否提出一個替代方案? *請注意,我沒有試圖檢查延期,但內容。在ASP.Net驗證IFormFile的圖像類型核心

謝謝

+0

http://stackoverflow.com/questions/3643750/net-image-libraries –

回答

0

,如果你有特權,你可以使用ImageMagick的標識命令的服務器上運行的可執行文件。這是很多工作。你需要在服務器上安裝imagemagick,並且需要有權限運行可執行文件。

https://www.imagemagick.org/script/identify.php

你需要調用程序並給出該圖像文件將其

如何調用在C#中的EXE文件:https://msdn.microsoft.com/en-us/library/0w4h05yb(v=vs.110).aspx

如何閱讀過程輸出:https://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline(v=vs.110).aspx

+0

我真的需要一種方式在C#代碼.... – Techy

-1

你可以查看這個post,我試過了..

 // declare FindMimeFromData from urlmon.dll 
    [DllImport(@"urlmon.dll", CharSet = CharSet.Unicode)] 
    private extern static System.UInt32 FindMimeFromData(System.UInt32 pBC, 
    [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl, 
    [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer, 
    System.UInt32 cbSize, 
    [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed, 
    System.UInt32 dwMimeFlags, 
    out System.IntPtr ppwzMimeOut, 
    System.UInt32 dwReserverd 
    ); 


    // you can return boolen value if mime type is not image 
    public static string getMimeFromFile(IFormFile file) 
    { 


     byte[] buffer = new byte[256]; 
     using (Stream fs = file.OpenReadStream()) 
     { 
      if (fs.Length >= 256) 
       fs.Read(buffer, 0, 256); 
      else 
       fs.Read(buffer, 0, (int)fs.Length); 
     } 
     try 
     { 
      //System.UInt32 mimetype; 
      IntPtr mimetype = Marshal.AllocHGlobal(256); 
      FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0); 
      //System.IntPtr mimeTypePtr = new IntPtr(mimetype); 
      string mime = Marshal.PtrToStringUni(mimetype); 
      Marshal.FreeCoTaskMem(mimetype); 
      return mime; 
     } 
     catch (Exception e) 
     { 
      return "unknown/unknown"; 
     } 
    } 

    [HttpGet] 
    public ActionResult Test() 
    { 

     ViewData["Message"] = "Your test page."; 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Test(IFormFile file) 
    { 
     string mimeType = getMimeFromFile(file); 
     ViewData["Message"] = mimeType; 
     return View(); 
    } 

和Test.cshtml

<h3>@ViewData["Message"]</h3> 
<form action="/Home/Test" method="post" enctype="multipart/form-data"> 

    <input name="file" type="File"> <br> 
    <input type="submit" value="submit"> 

</form> 

UPDATE:

如果你不能使用DLL導入了跨平臺,檢查this。您可以從here添加新的MIME類型。

+0

如果你相信一個問題要回答的另一個問題的答案,唐不要複製上述問題的答案,而是將此問題標記爲重複。但這是關於ASP.NET Core的,前提是它可以在任何運行時運行。通過涉及平臺調用,您否定了這一點。 – CodeCaster

+0

@CodeCaster它不復制粘貼。在談論它之前請閱讀代碼 – levent

+0

我需要它來接受所有圖像請 – Techy