Asp.net 限制要上载的文件类型

Asp.net 限制要上载的文件类型,asp.net,file-upload,file-type,Asp.net,File Upload,File Type,我已经删除了我先前关于使用经典asp上传文件的问题。现在我已经切换到.net以实现这一目标,但我仍然无法限制文件类型,即pdf和docx正在上载 代码如下所示: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; public parti

我已经删除了我先前关于使用经典asp上传文件的问题。现在我已经切换到.net以实现这一目标,但我仍然无法限制文件类型,即pdf和docx正在上载

代码如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class CS : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string[] filePaths = Directory.GetFiles(Server.MapPath("~/Upload/"));
            List<ListItem> files = new List<ListItem>();
            foreach (string filePath in filePaths)
            {
                files.Add(new ListItem(Path.GetFileName(filePath), filePath));
            }
            GridView1.DataSource = files;
            GridView1.DataBind();
        }
    }
    protected void UploadFile(object sender, EventArgs e)
    {
        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Upload/") + fileName);
        Response.Redirect(Request.Url.AbsoluteUri);
    }
    protected void DownloadFile(object sender, EventArgs e)
    {
        string filePath = (sender as LinkButton).CommandArgument;
        Response.ContentType = ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
        Response.WriteFile(filePath);
        Response.End();
    }
    protected void DeleteFile(object sender, EventArgs e)
    {
        string filePath = (sender as LinkButton).CommandArgument;
        File.Delete(filePath);
        Response.Redirect(Request.Url.AbsoluteUri);
    }
} 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="safetyupload.aspx.cs" Inherits="CS" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="UploadFile" />
    <hr />
   <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">
        <Columns>
            <asp:BoundField DataField="Text" HeaderText="File Name" />

            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID = "lnkDelete" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>
请建议解决方案。

使用后,您可以获得类似

string fileExtension = Path.GetExtension(fileName);
        fileExtension = fileExtension.ToLower();
        string[] acceptedFileTypes = { ".docx", ".pdf"  };
        bool acceptFile = false;

        for (int i = 0; i <= 1; i++) 
        {
            if (fileExtension == acceptedFileTypes[i])
            {
                acceptFile = true;
            }
        }

        if (!acceptFile)
        {
            Label1.Text = "You error message here";
            return;
        }
stringfileextension=Path.GetExtension(文件名);
fileExtension=fileExtension.ToLower();
字符串[]acceptedFileTypes={.docx',.pdf};
bool-acceptFile=false;

对于(int i=0;i您现有的
UploadFile
方法位于正确的行上,但是在选中
FileUpload.PostedFile.ContentType
的地方,此属性包含上载文件的类型。PDF的正确MIME类型为
application/PDF
(如中所述;正是文件中的二进制数据使其成为PDF,而不仅仅是扩展名为“PDF”(顺便说一句,您还希望大量使用
.ToLowerInvariant
进行比较,否则“PDF”文件扩展名不会被查找“PDF”的内容所捕获).对于docx文件,要在代码中查找的MIME类型是
application/vnd.openxmlformats officedocument.wordprocessingml.document
()。因此,您的代码如下所示:

protected void UploadFile(object sender, EventArgs e)
{
    // Build a list of whitelisted (acceptable) MIME types
    // This list could be driven from a database or external source so you can change it without having to recompile your code
    List<string> whiteListedMIMETypes = new List<string>();
    whiteListedMIMETypes.Add("application/pdf");
    whiteListedMIMETypes.Add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

    if (FileUpload1.HasFile)
    {
        try
        {
            // Check the list to see if the uploaded file is of an acceptable type
            if (whiteListedMIMETypes.Contains(FileUpload1.PostedFile.ContentType.ToLowerInvariant()))
            {
                string fileName = Path.GetFileName(FileUpload1.FileName);
                FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Upload/") + fileName);
                Response.Redirect(Request.Url.AbsoluteUri);
            }
            else
                Label1.Text = "Unacceptable file type";
        }
        catch (Exception ex)
        {
            Label1.Text = "Error during uploading the file";
        }
    }
}
受保护的无效上载文件(对象发送方,事件参数e)
{
//构建白名单(可接受)MIME类型的列表
//此列表可以从数据库或外部源驱动,因此您无需重新编译代码即可对其进行更改
List WhiteListAdminetypes=新列表();
添加(“application/pdf”);
Add(“application/vnd.openxmlformats of cedocument.wordprocessingml.document”);
if(FileUpload1.HasFile)
{
尝试
{
//检查列表以查看上载的文件是否为可接受的类型
if(WhiteListDmitypes.Contains(FileUpload1.PostedFile.ContentType.ToLowerInvariant())
{
字符串fileName=Path.GetFileName(FileUpload1.fileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath(“~/Upload/”)+fileName);
重定向(Request.Url.AbsoluteUri);
}
其他的
Label1.Text=“不可接受的文件类型”;
}
捕获(例外情况除外)
{
Label1.Text=“上传文件时出错”;
}
}
}

一般来说,你不应该仅仅通过查看文件的扩展名来确定文件的类型-用户可以按照任何方式重命名文件和扩展名,但是如果我将我的
FileStealingVirus.exe
重命名为
FileStealingVirus.pdf
,该文件仍然是一个窃取文件的病毒,而不是pdf文档。如果我知道你只是查看上传文件的扩展名,我知道我可以通过伪装成PDF上传病毒,然后我可以窃取您的文件!

请看:Ehsan先生,在您建议的示例中,您仅给出验证错误消息,指示无效文件,但是,任何类型的文件都可以上传。对不起,我不是专业人士。如果可能,请e在此给出完整的代码修改。请……使用此命令,我得到错误“CS1061:'System.Web.UI.HtmlControl.HtmlGenericControl”不包含“Text”的定义,并且找不到接受类型为“System.Web.UI.HtmlControl.HtmlGenericControl”的第一个参数的扩展方法“Text”(您是否缺少using指令或汇编引用?)“在我的机器上运行得非常好:/还要注意@PhilPursgolve answer。他指出了一些非常有用的提示。
protected void UploadFile(object sender, EventArgs e)
{
    // Build a list of whitelisted (acceptable) MIME types
    // This list could be driven from a database or external source so you can change it without having to recompile your code
    List<string> whiteListedMIMETypes = new List<string>();
    whiteListedMIMETypes.Add("application/pdf");
    whiteListedMIMETypes.Add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

    if (FileUpload1.HasFile)
    {
        try
        {
            // Check the list to see if the uploaded file is of an acceptable type
            if (whiteListedMIMETypes.Contains(FileUpload1.PostedFile.ContentType.ToLowerInvariant()))
            {
                string fileName = Path.GetFileName(FileUpload1.FileName);
                FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Upload/") + fileName);
                Response.Redirect(Request.Url.AbsoluteUri);
            }
            else
                Label1.Text = "Unacceptable file type";
        }
        catch (Exception ex)
        {
            Label1.Text = "Error during uploading the file";
        }
    }
}