0

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 i.e. 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.

2
  • see this:c-sharpcorner.com/UploadFile/99bb20/… Commented Nov 10, 2014 at 10:56
  • Ehsan Sir, in example suggested by you just only giving validation error message indicating an invalid file, however, file of any type can be uploaded. Commented Nov 10, 2014 at 11:38

2 Answers 2

1

Use Path.GetExtension Then you can have something like

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; } 
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, I am not an professional one. If possible please give complete code modification here. Please......
Using this I got the error " CS1061: 'System.Web.UI.HtmlControls.HtmlGenericControl' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'System.Web.UI.HtmlControls.HtmlGenericControl' could be found (are you missing a using directive or an assembly reference?)"
Works perfectly fine for me on my machine :/ Also take into note of @PhilPursgolve answer. He has pointed out some really useful tips.
1

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.