pdf和rar文件没有上传但图像有

时间:2012-10-08 07:09:29

标签: c# asp.net

我一直在使用asp.net webforms控件来学习如何更好地使用它们,而且我似乎在使用fileupload控件遇到了一些麻烦。我注意到,当我上传img时,我编写的代码有效,但当我尝试上传PDF或RAR文件时,我收到错误说

  

与localhost的连接已被中断

这是我的代码:

<div id="center">
       <asp:FileUpload ID="FileUpload1" runat="server" />
       <br />
       <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
       <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>


protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile) {
            try
            {
                string filename = FileUpload1.FileName;
                FileUpload1.SaveAs(Server.MapPath("~/Files/") + filename);
                Label1.Text = "File has been uploaded";
            }
            catch (Exception ex) {
                Label1.Text = "The file could not be uploaded";
            }
        }   
    }

有什么问题?为什么我不能上传其他文件类型?

2 个答案:

答案 0 :(得分:2)

当您尝试上传超过默认最大大小(即4MB)的文件时,您可能会在页面重置或中断时结束。您可以在配置文件中设置最大大小。

<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>

Fileupload控件在这里讨论得很好。 http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx

答案 1 :(得分:1)

尝试上传文件扩展名,如下所示:

protected void Button1_Click(object sender, EventArgs e) 
    { 
        if (FileUpload1.HasFile) { 
            try 
            { 
                string filename = FileUpload1.FileName; 
                FileUpload1.SaveAs(Server.MapPath("~/Files/") + filename + System.IO.Path.GetExtension(FileUp.PostedFile.FileName); 
                Label1.Text = "File has been uploaded"; 
            } 
            catch (Exception ex) { 
                Label1.Text = "The file could not be uploaded"; 
            } 
        }    
    }