Restrict file type to be upload
I have deleted my earlier question regarding file upload using classic asp. Now I have switched to .net for achieve the goal however I am still unable to restrict file type ie pdf & docx being upload.
code behind is as under:
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 is as under:
<%@ 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>
I have tried this but no avail
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";
}
}
}
Please suggest solutions.
使用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;
}
Your existing UploadFile
method is on the right lines, however where you check FileUpload.PostedFile.ContentType
, this property contains the MIME type of the uploaded file. The correct MIME type for a PDF is application/pdf
(as specified in this question; it's the binary data inside the file that makes it a PDF, not just that it has the extension 'pdf' (incidentally, you also want to liberally use .ToLowerInvariant
for your comparisons, otherwise a 'PDF' file extension won't get trapped by something looking for 'pdf'). For docx files the MIME type to look for in code is application/vnd.openxmlformats-officedocument.wordprocessingml.document
(reference). So your code would look like:
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";
}
}
}
As a general point you shouldn't rely on just looking at the extension of a filename to determine its' type - users can rename files and extensions any way they want, but if I rename my FileStealingVirus.exe
to FileStealingVirus.pdf
, the file is still a file-stealing virus, not a PDF document. If I know you're only checking the extension of the uploaded file, I know I can upload my virus by disguising it as a PDF and then I can steal your files!
上一篇: 某些PDF文件(空的MIME类型)导致PHP上传失败
下一篇: 限制要上传的文件类型