限制要上传的文件类型

我已经删除了我之前关于使用传统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);
    }
} 

html页面如下所示:

<%@ 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>

我试过这个,但没有用

protected void UploadFile(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {
                if (FileUpload.PostedFile.ContentType == "pdf")
                {
                    string fileName = Path.GetFileName(FileUpload1.FileName);
                    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Upload/") + fileName);
                    Response.Redirect(Request.Url.AbsoluteUri);
                }
                else
                    Label1.Text = "PDF files only";
            }
            catch (Exceptionex)
            {
                Label1.Text = "Error during uploading the file";
            }
        }
    }

请建议解决方案。


使用Path.GetExtension然后你可以有类似的东西

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

您现有的UploadFile方法位于右侧,但在您检查FileUpload.PostedFile.ContentType ,此属性包含上载文件的MIME类型。 PDF的正确MIME类型是application/pdf (如此问题中指定的;它是文件内的二进制数据,它使其成为PDF,而不仅仅是它具有扩展名'pdf'(顺便说一句,您还想宽松地使用.ToLowerInvariant用于比较,否则'PDF'文件扩展名不会被寻找'pdf'的东西所困住)。对于docx文件,在代码中查找的MIME类型是application/vnd.openxmlformats-officedocument.wordprocessingml.document (reference)。所以你的代码看起来像这样:

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

作为一个普遍的观点,你不应该仅仅依靠文件名的扩展名来确定它的类型 - 用户可以以他们想要的方式重命名文件和扩展名,但是如果我将FileStealingVirus.exe重命名为FileStealingVirus.pdf ,那么文件仍然是一个文件窃取病毒,而不是PDF文件。 如果我知道你只是检查上传文件的扩展名,我知道我可以通过伪装成PDF来上传我的病毒,然后我可以窃取你的文件!

链接地址: http://www.djcxy.com/p/8191.html

上一篇: Restrict file type to be upload

下一篇: How to open a pdf url which does not have a .pdf extension?