图片上传:FileUpload未引用实例、大容量上传
今日通过FileUpload上传一5,199 KB 的图片时,前台代码:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="WebFile" runat="server" Height="23px" />
<asp:Button ID="pictureUp" runat="server" onclick="pictureUp_Click" Text="上传文件" OnClientClick = "return sureExecutecode1()" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="pictureUp" />
<asp:PostBackTrigger ControlID="pictureClear" />
</Triggers>
</asp:UpdatePanel>
后台代码如下:
protected void pictureUp_Click(object sender, EventArgs e)
{
if (WebFile.PostedFile.FileName == "")
{
string script1 = "if(alert('请选择要上传的文件!')) ";
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alertForm", script1, true);
return;
}
try
{
string strName = WebFile.PostedFile.FileName;//使用fileupload控件获取上传文件的文件名
if (strName != "")//如果文件名存在
{
int i = strName.LastIndexOf(".");//获取。的索引顺序号,在这里。代表图片名字与后缀的间隔
string kzm = strName.Substring(i);//获取文件扩展名
string newName = "";
Label21.Text = RadioButtonList3.SelectedItem.Text.ToString() + lailiaonum.Text.ToString();
if(Label21.Text != "")
{
newName = Label21.Text.ToString();
}
else if (Label2.Text != "")
{
newName = Label2.Text.Trim();
}
string xiangdui = @"~/goodsPhtot/";//设置文件相对网站根目录的保存路径 ,~号表示当前目录,在此表示根目录下的images文件夹
string juedui = Server.MapPath("~//goodsPhtot//");//设置文件保存的本地目录绝对路径,对于路径中的字符“\”在字符串中必须以“\\”表示,因为“\”为特殊字符。或者可以使用上一行的给路径前面加上@
string newFileName = juedui + newName + kzm;
WebFile.PostedFile.SaveAs(newFileName);//将图片存储到服务器上
Image1.Visible = true;//最开始我们把图片的属性设置为不可见,是为了美观,在这要显示,所以就设置为可见
LAB.Text = xiangdui + newName + kzm;
Image1.ImageUrl = xiangdui + newName + kzm;//当图片属性为可见时,就要设置图片的链接地址。在这里,一定要写图片的相对路径,因为要显示的是已经传在服务器上的图片
string script1 = "if(alert('货物照片添加已成功!')) ";
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alertForm", script1, true);
}
}
catch
{
string script1 = "if(alert('上传文件失败,请与管理员联系!')) ";
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alertForm", script1, true);
}
}
突然出现了这样的界面
刚开始还以为代码问题,但是觉得不可能,因为前一天还是成功的。迷迷糊糊的把,前台的一句代码,如下所示,给去掉了
<Triggers>
<asp:PostBackTrigger ControlID="pictureUp" />
</Triggers>
就出现了另一个问题,WebFile没有引用到实例。这里注意,触发器是必须加的。
是换了一张图片却成功了,推断不是代码问题,突然想起,ASP.NET 支持的HTTP方式上传的默认最大字节数为 4096 KB (4 MB),用于防止因用户将大量文件传递到服务器而导致的拒绝服务攻击。故而采用如下的方式:
增大字节数,修改web.config文件,代码如下:
<system.web>
<!--设置 compilation debug="true" 可将调试符号插入
已编译的页面中。但由于这会
影响性能,因此只在开发过程中将此值
设置为 true。
<customErrors mode="Off" />
<httpRuntime executionTimeout ="9999" maxRequestLength ="2097151"/>
</system.web>
注:executionTimeout: 表示ASP.NET被自动关闭前,允许执行请求的最大秒数。在当文件超出指定的大小时,如果浏览器中产生 DNS 错误或者出现服务不可得到的情况,可以挺过修改以上的配置,增大配置数来解决。maxRequestLength:指示 ASP.NET 支持的HTTP方式上载的最大字节数。
经过修改后,即可上传成功
转载于:https://my.oschina.net/starmier/blog/142462