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";
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With