c# - 如何上传 pdf 文件?

标签 c# asp.net file-upload

我必须使用 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";
 }

最佳答案

您应该重构您的代码,以便它可以准确地告诉您上传有什么问题。像这样:

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

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

关于c# - 如何上传 pdf 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8411119/

相关文章:

c# - 在运行时动态添加 C# 属性

javascript - asp.net 2.0 中的跨浏览器文件输入验证

asp.net - AJAX post 中的 HttpWebRequest 之后 session 状态丢失

c# - 解决方案范围#define

c# - 如何使用C#获取简单的指纹图像

c# - c#中如何获取当前执行方法的输出参数列表?

javascript - 使用单独的 Dropzones 以一种形式上传多个单个文件

asp.net - Telerik RadOrgChart 节点点击事件

tomcat - 如何在 Tomcat 上运行的 servlet 过滤器中使用 HttpServletRequest#getParts()?

python - 如果不允许内容类型,如何丢弃上传的文件?