008. 限制上传文件的大小
生活随笔
收集整理的這篇文章主要介紹了
008. 限制上传文件的大小
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一種方法:
利用web.config的配置文件項, 進行設置;
前端aspx示例:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="sendOutEmail.aspx.cs" Inherits="sendOutEmail" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head ><title>文件上傳</title> </head> <body><form id="form1" runat="server"><div><table ><tr><td ><asp:FileUpload ID="FileUp" runat="server" Width="456px" style="border: 1px solid red" Height="21px"/></td></tr><tr><td><asp:Button ID="BtnSend" runat="server" OnClick="ImgBtnSend_Click" Text="提交" /> <asp:Button ID="Btnchongzhi" runat="server" Text="重置" CausesValidation="False" onclick="Btnchongzhi_Click" /><asp:Label ID="LblMessage" runat="server" ForeColor="Red" Width="88px" /></td></tr></table></div></form> </body> </html>后端cs文件的部分內容:
protected void ImgBtnSend_Click(object sender, EventArgs e){string filepath = FileUp.PostedFile.FileName; //獲取客戶端上傳文件的文件的路徑,即FileUpload控件文本框中的所有內容//FileUp.FileName 只獲取上傳文件的文件名string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);string serverpath = Server.MapPath("~/") + filename; //返回服務器上與指定虛擬路徑對應的物理路徑FileUp.PostedFile.SaveAs(serverpath);//將文件保存到服務器上LblMessage.Text = "恭喜您!文件上傳成功!";}web.config文件中的部分內容
<system.web> <!--設置上傳文件的最大 大小 為4M, 超時時間為100秒--><httpRuntime maxRequestLength="4096" executionTimeout="100"/> </system.web>第二種方法: 通過編程的形式限制上傳文件的大小, 這里將其顯示為1MB為例;前端代碼不變, 后端稍加修改
protected void Button1_Click(object sender, EventArgs e){//獲取客戶端上傳文件的文件的路徑,即FileUpload控件文本框中的所有內容string filepath = FileUp.PostedFile.FileName;//FileUp.FileName 只獲取上傳文件的文件名string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);if (FileUp.PostedFile.ContentLength > 1024000){LblMessage.Text = "文件大小不能超過1MB!";}else{//返回服務器上與指定虛擬路徑對應的物理路徑string serverpath = Server.MapPath("~/") + filename;FileUp.PostedFile.SaveAs(serverpath);LblMessage.Text = "恭喜您!文件上傳成功!";}}注: 上傳文件時, 有時瀏覽器會報如下錯誤, 沒有關系, 清空下緩存或者換個瀏覽器就好了
轉載于:https://www.cnblogs.com/wxylog/p/6039547.html
總結
以上是生活随笔為你收集整理的008. 限制上传文件的大小的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OPPO首款智能猫砂盆官宣:一体化结构不
- 下一篇: 至少15种奥密克戎变异株现身国内!BA.