我必须使用FileUpload
控件在Web应用程序中上传.pdf文件。我试过这段代码,但它有一些问题。任何人都可以帮我这个吗?
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";
}
答案 0 :(得分:6)
您应该重新构建代码,以便它可以准确地告诉您上传的错误。像这样:
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.";
}
我的猜测是浏览器没有提供正确的内容/类型。试试上面的代码并告诉我们你得到的信息。
答案 1 :(得分:3)
<INPUT id="FileUp" type="file" name="File1" runat="server">
if(FileUp.PostedFile.ContentLength > 0)
{
string ext = System.IO.Path.GetExtension(FileUp.PostedFile.FileName);
if(ext=="pdf"){
string Filename=YourFileName+ext;
FilePath=Server.MapPath("..") + "\\path\\toyourfile\\" + Filename;
FileUp.PostedFile.SaveAs(FilePath);
Label6.Text = "File Uploaded Successfully...";
}
}
答案 2 :(得分:3)
您只需替换以下代码行
if (FileUpload1.PostedFile.ContentType == ".pdf")
使用此
if (FileUpload1.PostedFile.ContentType == "application/pdf")
并且您的代码运行正常。