Home > Forum > ASP.NET > uploading a pdf file

uploading a pdf file

by gautam datta   on Dec 16, 2013   Category: ASP.NET  |  Views: 1442    |  Points: 5   |  Starter 
  Reply
How can i Upload a PDF File in my website.(C# coding)

Bookmark and Share:
 
  User Reply  | Ask a question  |   Reply 
  Re :uploading a pdf file   
by Thamil
on Dec 22 2013 2:02AM
Points : 10
Gold 
Hi gautam datta,

Please see the below code snippet to upload only pdf files

Aspx page
<div>
<asp:FileUpload ID="FileUploadToServer" Width="300px" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click"
ValidationGroup="vg" Style="width: 99px" />
<br />
<br />
<asp:Label ID="lblMsg" runat="server" ForeColor="Green" Text=""></asp:Label>
<br />
</div>

Code behind part
protected void btnUpload_Click(object sender, EventArgs e)
{
//Get path from web.config file to upload
string FilePath = Server.MapPath("~/UploadFiles/");
string filename = string.Empty;
//To check whether file is selected or not to uplaod
if (FileUploadToServer.HasFile)
{
try
{
string[] allowdFile = { ".pdf"};
//Here we are allowing only pdf file so verifying selected file pdf or not
string FileExt = System.IO.Path.GetExtension(FileUploadToServer.PostedFile.FileName);
//Check whether selected file is valid extension or not
bool isValidFile = allowdFile.Contains(FileExt);
if (!isValidFile)
{
lblMsg.ForeColor = System.Drawing.Color.Red;
lblMsg.Text = "Please upload only pdf";
}
else
{
// Get size of uploaded file, here restricting size of file
int FileSize = FileUploadToServer.PostedFile.ContentLength;
if (FileSize <= 1048576)//1048576 byte = 1MB
{
//Get file name of selected file
filename = Path.GetFileName(Server.MapPath(FileUploadToServer.FileName));

//Save selected file into server location
FileUploadToServer.SaveAs(FilePath + filename);

}
else
{
lblMsg.Text = "Attachment file size should not be greater then 1 MB!";
}
}
}
catch (Exception ex)
{
lblMsg.Text = "Error occurred while uploading a file: " + ex.Message;
}
}
else
{
lblMsg.Text = "Please select a file to upload.";
}
}


I hope above code will help you on this.

Recent Post

Latest Posts