如何上传只有JPEG文件? [英] How can i upload only jpeg files?

查看:148
本文介绍了如何上传只有JPEG文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要上传了仅JPEG,JPG等文件,但我不能在打开的窗口中的文件进行筛选。我想改变文本所有文件到jpeg等在asp.net。 (C#)

i want to upload files that are only jpeg, jpg etc. But i couldn't filter the files in the opening window. I want to change the text "all files" to jpeg etc. in the asp.net. (C#)

推荐答案

您可以使用RegularEx pressionValidator验证如果用户试图上传的JPEG文件或不:

You could use a RegularExpressionValidator to validate if the user tries to upload jpeg-files or not:

<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" 
 Text="Upload File" />&nbsp;<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:RegularExpressionValidator 
 id="RegularExpressionValidator1" runat="server" 
 ErrorMessage="Only jpeg files are allowed!" 
 ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))
    +(.jpg|.JPG|.jpeg|.JPEG)$" 
 ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>
<br />
<asp:RequiredFieldValidator 
 id="RequiredFieldValidator1" runat="server" 
 ErrorMessage="This is a required field!" 
 ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>

在服务器端:

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileExt = 
               System.IO.Path.GetExtension(FileUpload1.FileName);

            if (fileExt == ".jpeg" || fileExt == ".jpg")
            {
                //do what you want with this file
            }
            else
            {
                Label1.Text = "Only .jpeg files allowed!";
            }
        }
        else
        {
            Label1.Text = "You have not specified a file.";
        }
    }

您应该知道,任何用户可以更改扩展名F.E.从.exe文件到JPG。我知道检查的实际文件类型的唯一方法是使用函数从 Urlmon.dll的。看看这个所谓的问题,如果您想了解更多信息:<一href=\"http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature\">Using .NET,你怎么能找到基于文件签名没有扩展名的文件的MIME类型。

You should know that any user could change the extension f.e. from .exe to .jpg. The only way i know to check for the real file-type would be to use function from Urlmon.dll. Have a look at this SO-question if you want further informations: Using .NET, how can you find the mime type of a file based on the file signature not the extension.

这篇关于如何上传只有JPEG文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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