是否可以验证发布的文件是否为pdf? [英] Is it possible to verify that a posted file is pdf or not?

查看:87
本文介绍了是否可以验证发布的文件是否为pdf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有意识的网站的主要工作是接受来自用户的文件并保存.直到2个月前,当我被告知强制执行一项仅接受pdf文件的约束时,一切都很好.

The conserned website primary work is to accept files from users and save it. Every thing was fine till 2 months back when i was told to enforce a constraint to accept only pdf files.

在用户习惯于提交从text,rtf到pdf格式的各种格式之前.

Before that users were in the habit of submitting various formats from text,rtf to good pdf.

我通过检查文件扩展名来应用约束-简单正确吗?但是,当管理员检查这些文件时,有60%的文件已损坏.

I applied the constraint by checking the file extention --simple right?? however when the admin checked those files some good 60% of the files were corrupt.

我花了许多不眠之夜来确定腐败的原因,然后突然间我以为可能是他们提交了损坏的文件.

I spent many sleepless nights to determine the cause of curruption then suddenly i thought may be they are submitting corrupt files.

我记录了以前的记录,并从我们收到损坏文件的那位用户中确定了某些用户喜欢的文件类型格式.

I took the previous records and determined the favourite format of file type of some users from whome we were getting corrupt files.

我将扩展名改回了最喜欢的扩展名和繁荣.文件打开了.

I changed the extention back to there favourite extention and boom.. the file opened.

我了解到的是,尽管粗体地告诉用户如何将其中的文件转换为pdf,但一些(许多)只是在更改扩展范围并提交. 由于该网站奖励用户没有.文件提交的管理人员对我发牢骚.有什么办法可以不依靠扩展名来检查文件是否为pdf ??

what I came to know however dispite telling in bold to user how to convet there files to pdf some(many) were just changing the extention and submitting. Since the website rewards the users on no. of file submitted administration people are grunting at me. Is there any way i can check the file is pdf or not without relying on the extention??

我正在c#3.5 asp.net中使用fileupload

I am using fileupload in c# 3.5 asp.net

推荐答案

由于所有PDF文件均以ASCII字符串%PDF-"开头,因此只需测试文件的前几个字节,以确保它们以该字符串开头.

As all PDF files start with the ASCII string "%PDF-", simply test the first few bytes of the file to ensure that they start with this string.

bool IsPdf(string path)
{
    var pdfString = "%PDF-";
    var pdfBytes = Encoding.ASCII.GetBytes(pdfString);
    var len = pdfBytes.Length;
    var buf = new byte[len];
    var remaining = len;
    var pos = 0;
    using(var f = File.OpenRead(path))
    {
        while(remaining > 0)
        {
            var amtRead = f.Read(buf, pos, remaining);
            if(amtRead == 0) return false;
            remaining -= amtRead;
            pos += amtRead;
        }
    }
    return pdfBytes.SequenceEqual(buf);
}

这篇关于是否可以验证发布的文件是否为pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆