【问题标题】:Razor Page IFormFile .Net 5.0 attachment Header ValidationRazor 页面 IFormFile .Net 5.0 附件标题验证
【发布时间】:2021-05-07 05:07:06
【问题描述】:

我使用 .Net 5.0 (Razor Pages) 和 IFormFile 上传用户图像,在 ASP.NET 中我用来验证文件的标题以确保上传的文件有效,例如不更改 EXE文件扩展名到 Jpg 并将其上传,以便验证 IFormFile 的标头有帮助吗?

在 ASP.NET 中使用的功能:我需要在 Razor Pages 中实现

public string validateFileToUpload(FileUpload objFile)
    {
        string errorMessageToReturn = string.Empty;
        // DICTIONARY OF ALL IMAGE FILE HEADER
        Dictionary<string, byte[]> imageHeader = new Dictionary<string, byte[]>();
        imageHeader.Add("JPG", new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 });
        imageHeader.Add("JPEG", new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 });

        imageHeader.Add("PDF", new byte[] { 0x25, 0x50, 0x44, 0x46 });
        imageHeader.Add("DOCX", new byte[] { 0x50, 0x4B, 0x03, 0x04 });
        imageHeader.Add("DOC", new byte[] { 0xD0, 0xCF, 0x11, 0xE0 });
        imageHeader.Add("MSG", new byte[] { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 });

        byte[] header;

       
        string fileExt;
        fileExt = objFile.FileName.Substring(objFile.FileName.LastIndexOf('.') + 1).ToUpper();

       
        byte[] tmp;
        try
        {
            tmp = imageHeader[fileExt];
            header = new byte[tmp.Length];
        }
        catc
        {
            errorMessageToReturn = "Invalid File.";
            return errorMessageToReturn;
        }
        

        
        objFile.FileContent.Read(header, 0, header.Length);

        if (CompareArray(tmp, header))
        {
            errorMessageToReturn = string.Empty;
        }
        else
        {
            errorMessageToReturn = "Invalid ." + fileExt + " file.";
            
        }

        return errorMessageToReturn;
    }

    private bool CompareArray(byte[] a1, byte[] a2)
    {
        if (a1.Length != a2.Length)
            return false;

        for (int i = 0; i < a1.Length; i++)
        {
            if (a1[i] != a2[i])
                return false;
        }

        return true;
    }

【问题讨论】:

  • 嗨@Allam,验证文件扩展名怎么样?
  • 我需要一个函数来验证文件头和文件扩展名
  • 嗨@Allam,您要验证哪个标头?您的意思是Content-Type=multipart/form-data
  • 亲爱的 Rena,感谢您的回复,下面是我在 asp.net 中验证文件时调用的函数,我需要在 Razor 页面中实现相同的函数,但 iFormFile 不返回头文件

标签: asp.net validation .net-core upload iformfile


【解决方案1】:

已使用以下解决方案,而不是 objFile.FileContent.Read(header, 0, header.Length);

if (objFile.Length > 0)
            {
                using (var ms = new MemoryStream())
                {
                    objFile.CopyTo(ms);
                    var fileBytes = ms.ToArray();

                for (int i = 0; i < header.Length; i++)
                {
                    header[i] = fileBytes[i];
                }
                
                }
            }

【讨论】:

    猜你喜欢
    • 2021-05-31
    • 2022-12-31
    • 2019-06-22
    • 2021-11-07
    • 2021-11-08
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    相关资源
    最近更新 更多