Ni Ru Ni Ru - 1 year ago 94
ASP.NET (C#) Question

How can I upload a pdf file?

I have to upload a .pdf file in a web application using the

FileUpload
control. I have tried this code, but it has some problems. Can anyone help me with this?

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == ".pdf")
{
string path = Server.MapPath(".") + "\\" + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(path);
Label6.Text = "File Uploaded Successfully...";
StreamReader reader = new StreamReader(FileUpload1.FileContent);
string text = reader.ReadToEnd();
}
else
Label6.Text = "Upload .pdf File";
}
else
Label6.Text = "Upload file";
}

Answer Source

You should restructure your code so that it can tell you exactly what's wrong with the upload. Something like this:

 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", StringComparison.OrdinalIgnoreCase))
        return "Only PDF files are supported. Uploaded File Type: " + FileUpload1.PostedFile.ContentType;

    //rest of the code to actually process file.

    return "File uploaded successfully.";
 }

My guess is that the browser is not supplying correct content/type. Try the above code and tell us the message you get.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download