How can i upload only jpeg files?

两盒软妹~` 提交于 2019-12-08 05:25:15

问题


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


回答1:


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>

on serverside:

    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.";
        }
    }

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




回答2:


  • How do I validate the file type of a file upload
  • Check file extension of FileUpload control

Those will probably help you.




回答3:


This is not posible in the current HTML versions.

You should check uploaded files type on the server side.



来源:https://stackoverflow.com/questions/4702811/how-can-i-upload-only-jpeg-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!