限制要上载的文件类型

时间:2014-11-10 10:49:13

标签: 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 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";
            }
        }
    }

请提出解决方案。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您现有的UploadFile方法位于右侧,但无论您在哪里检查FileUpload.PostedFile.ContentType,此属性都包含已上传文件的MIME type。 PDF的正确MIME类型为application/pdf(在this question中指定;它是文件中的二进制数据,使其成为PDF,而不仅仅是它具有扩展名&#39 ; pdf&#39;(顺便提一下,你也想要自由地使用.ToLowerInvariant进行比较,否则一个“PDF”文件扩展名不会被寻找的东西所困?&#39; pdf&#39;)。对于docx文件,要在代码中查找的MIME类型为application/vnd.openxmlformats-officedocument.wordprocessingml.documentreference)。所以您的代码如下所示:

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来上传我的病毒,然后我可以窃取您的文件!

相关问题