简体   繁体   English

验证Excel文件上传

[英]validating excel file upload

Please help me in validating excel file upload. 请帮助我验证excel文件上传。 I have done coding for uploadation of excel file, and i want to validate whether the file is really a excel or not . 我已经完成了用于上传excel文件的编码,并且我想验证该文件是否真的是excel。 I have also checked by renaming an x.exe file like x.exe.xls also by placing server side checking as given bellow but it failed. 我还通过重命名x.exe文件(如x.exe.xls)进行了检查,也通过将服务器端检查作为给定的方法进行了检查,但失败了。 My requirement is to upload only valid excel file and not any other file like .exe, .dll or exe file tampered as x.exe.xls etc as said before. 我的要求是仅上传有效的excel文件,而不上传任何其他文件(如.exe,.dll或exe文件被篡改为x.exe.xls等),如前所述。

if (fileUpload.PostedFile.ContentType == "application/vnd.ms-excel" ||

  fileUpload.PostedFile.ContentType == "application/excel" ||  

  fileUpload.PostedFile.ContentType == "application/x-msexcel" ||

 fileUpload.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" //this is xlsx format ) 

Something I used before: 我以前用过的东西:

    using System.Data.OleDb;

    public bool ValidateExcelFile(string fileName)
    {
        string connString = string.Format("Provider=Microsoft.Jet.OleDb.4.0; data source={0}; Extended Properties=\"Excel 8.0;HDR=Yes\"", fileName);
        OleDbConnection connection = null;
        try
        {
            connection = new OleDbConnection(connString);
            connection.Open();
            connection.Close();
            return true;
        }
        catch
        {
            return false;
        }
    }

If the file is not of actual Excel format, this will return false. 如果文件不是实际的Excel格式,则将返回false。

As Ray said, you'll have to check the magic bytes of the uploaded file. 正如Ray所说,您必须检查上传文件的魔术字节。 But this is going to cost a lot (computation time) 但这会花费很多(计算时间)

So I advise to first check that the file name and the ContentType are correct 所以我建议先检查一下文件名和ContentType是否正确

Please note that this will NOT allow you to reject files that would have been modified in the middle of the file (keeping the magic bytes intact...). 请注意,这将不允许您拒绝在文件中间进行修改的文件(保持魔术字节完好无损...)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM