我该如何上传PDF文件?

4

我需要在一个web应用程序中使用FileUpload控件上传一个.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";
 }

ContentType != 文件扩展名 - Brian Driscoll
程序直接进入else语句,而没有执行其他语句。 - Ni Ru
是的,因为ContentType永远不会是“.pdf”,因为它是一个文件扩展名而不是内容类型。 - Brian Driscoll
3个回答

7

您应该重构代码,以便可以准确地告诉您上传过程中出现的问题。例如:

 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.";
 }

我猜测是浏览器没有提供正确的内容/类型。请尝试使用上述代码并告诉我们您收到的消息。


是的,这对我来说很好,谢谢。我在网页上有一个“显示文件”(超链接按钮),当我点击它时,应该显示PDF文件,我该怎么做? - Ni Ru
我无法理解你的评论。你能再问一遍吗? - SolutionYogi
文件上传(上传文件)showfile(超链接) 提交(按钮点击)当我点击“showfile”链接时,我的网页就会显示我上传的PDF文件。 - Ni Ru
1
在这种情况下,您将不得不将上传的文件与用户关联,并在某个地方保存文件路径详细信息。这不能在评论中解释,请打开另一个问题以获得详细答案。 - SolutionYogi
我不能再问问题了,你能在这里给我答案吗? - Ni Ru

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...";
            }

        } 

3
您只需替换下面的代码行
if (FileUpload1.PostedFile.ContentType == ".pdf")

使用这个

if (FileUpload1.PostedFile.ContentType == "application/pdf")

你的代码运行正常。


我复制了你的代码,只是改了一行就在我的环境下工作了。 - sikender
我的意思是执行点直接进入else语句。 - Ni Ru
是的,现在它正常工作了,谢谢。我在网页上有一个“显示文件”(超链接按钮),当我点击它时,应该显示PDF文件,我该怎么做? - Ni Ru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接