简体   繁体   中英

validating excel file upload

Please help me in validating excel file upload. I have done coding for uploadation of excel file, and i want to validate whether the file is really a excel or not . 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. 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.

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.

As Ray said, you'll have to check the magic bytes of the uploaded file. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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