0

我一直在使用 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";
            }
        }   
    }

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

4

2 回答 2

2

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

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

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

于 2012-10-08T07:38:19.330 回答
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"; 
            } 
        }    
    } 
于 2012-10-08T07:46:15.417 回答