Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
can u give me the code to upload a pdf file using file upload
Posted
Comments
adriancs 8-Jan-14 2:33am    
for webform asp.net, you can use FileUpload.

your question is incomplete or having less information.which control you used.
i want to give you different ways:-
1]use file uploader controller with regular epression:-
XML
<asp:FileUpload ID="flUpld" runat="server" />
                <asp:RegularExpressionValidator
                    id="RegularExpressionValidator1" runat="server"
                    ErrorMessage="Only PDF files are allowed!"
                    ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf|.PDF)$"
                    ControlToValidate="flUpld" CssClass="text-red"></asp:RegularExpressionValidator>



2] Use ajax file uploader controller:-
XML
<ajaxtoolkit:ajaxfileupload id="AjaxFileUpload1" xmlns:ajaxtoolkit="#unknown">
    ThrobberID="myThrobber"
    ContextKeys="fred"
    AllowedFileTypes="jpg,pdf"
    MaximumNumberOfFiles=10
    runat="server"/></ajaxtoolkit:ajaxfileupload>


3] or use javascript script to validate file is .pdf
XML
<script type ="text/javascript">
    var validFilesTypes=["PDF","pdf"];
    function ValidateFile()
    {
      var file = document.getElementById("<%=FileUpload1.ClientID%>");
      var label = document.getElementById("<%=Label1.ClientID%>");
      var path = file.value;
      var ext=path.substring(path.lastIndexOf(".")+1,path.length).toLowerCase();
      var isValidFile = false;
      for (var i=0; i<validFilesTypes.length; i++)
      {
        if (ext==validFilesTypes[i])
        {
            isValidFile=true;
            break;
        }
      }
      if (!isValidFile)
      {
        label.style.color="red";
        label.innerHTML="Invalid File. Please upload a File with" +
         " extension:\n\n"+validFilesTypes.join(", ");
      }
      return isValidFile;
     }
</script>


this is simple file upload code you have to modify this code as per your requirement
C#
protected void UploadButton_Click(object sender, EventArgs e)
{
    if(FileUploadControl.HasFile)
    {
        try
        {
            string filename = Path.GetFileName(FileUploadControl.FileName);
            FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
            StatusLabel.Text = "Upload status: File uploaded!";
        }
        catch(Exception ex)
        {
            StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}



or you can use server side validation and code is here. but i recommend to use client side validation and simple uploading code-
make change in below code as per your requirement:-
C#
protected void btnUpload_Click(object sender, EventArgs e)
       {
           //Get path from web.config file to upload
           string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
           bool blSucces = false;
           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);
                   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(FileUploadToServer.FileName);
                           //Save selected file into specified location
                           FileUploadToServer.SaveAs(Server.MapPath(FilePath) + filename);
                           lblMsg.Text = "File upload successfully!";
                           blSucces = true;
                       }
                       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.";
           }
           //Store file details into database
           if (blSucces)
           {
               Updatefileinfo(filename, FilePath + filename);
           }
       }
 
Share this answer
 
C#
protected void Button1_Click(object sender, EventArgs e)
{
   Label6.Text = ProcessUploadedFile();
}

private string ProcessUploadedFile()
{
   if(!FileUpload1.HasFile)
       return "You must select a valid file to upload.";

   if(FileUpload1.ContentLength == 0)
       return "You must select a non empty file to upload.";

   //As the input is external, always do case-insensitive comparison unless you actually care about the case.
   if(!FileUpload1.PostedFile.ContentType.Equals("application/pdf", StringComparion.OrdinalIgnoreCase))
       return "Only files of type PDF is supported. Uploaded File Type: " + FileUpload1.PostedFile.ContentType;

   //rest of the code to actually process file.

   return "File uploaded successfully.";
}


hope this will help.
 
Share this answer
 
Comments
Member 10500918 8-Jan-14 1:24am    
yes i used this code..but instead of a pdf file as output it gives me the message "File uploaded successfully."
Gitanjali Singh 8-Jan-14 1:33am    
As your file is uploaded successfully,that's why its showing this message.What else do you need?
Member 10500918 8-Jan-14 3:02am    
i want to display my pdf file
Gitanjali Singh 8-Jan-14 3:25am    
just a filename or would you like to open it?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900