.aspx代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="文件上传.aspx.cs" Inherits="文件上传" %>
<!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 runat="server">
<script src="JS/jquery-1.8.3.js" type="text/javascript"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function () {
$("#FileUpload1").val("");//防止后退键重复提交
});
function checkSize(obj_file) {
var _size = obj_file.files[0].size; //获取上传文件大小
if (_size > 8000000) {
alert("超过8M");//限制上传文件大小
$(obj_file).focus();
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" οnchange="checkSize(this)" />
<asp:Button ID="Button1" runat="server" Text="上传" οnclick="Button1_Click" />
<asp:TextBox ID="txt_size" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
.aspx.cs代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class 文件上传 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if(FileUpload1.HasFile){
string _targPath=MapPath("~/upfiles/")+DateTime.Now.ToOADate()+Path.GetExtension(FileUpload1.FileName);//上传后修改文件名
FileUpload1.SaveAs(_targPath);
Response.Redirect(Request.RawUrl);//防止刷新页面重复提交
}
}
}
web.config有一条如下:
<httpRuntime maxRequestLength="8192" executionTimeout="180"/>第一项为文件大小单位kb,第二项为最大上传时间。
显示效果如下: