前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="web_upload" %>
<!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">
<title>无标题页</title>
</head>
<body>
<form id="Form1" runat="server">
<table width="350" border="1" cellpadding="0" cellspacing="0" bordercolor="#00CCFF" bordercolordark="#FFFFFF">
<tr>
<td colspan="2">
照片上传<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></td>
</tr>
<tr>
<td width="70%">
<input type="file" id="myFile" runat="server" size="50"></td>
<td align="center">
<asp:Button ID="Button1" runat="server" Text="上 传" OnClick="Button1_Click" Width="71px" /></td>
</tr>
</table>
</form>
</body>
</html>
后台:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class web_upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string photos = "..//photo";
if (this.myFile.PostedFile != null)
{
string photoName1 = myFile.PostedFile.FileName; //获取初始文件名
int i = photoName1.LastIndexOf("."); //取得文件名中最后一个"."的索引
string newext = photoName1.Substring(i); //获取文件扩展名
if (newext != ".gif" && newext != ".jpg" && newext != ".jpeg" && newext != ".bmp" && newext != ".zip" && newext != ".doc" && newext != ".swf")
{
Response.Write("文件格式不正确!");
Response.End();
}
DateTime now = DateTime.Now; //获取系统时间
string photoName2 = now.Millisecond.ToString() + "_" + myFile.PostedFile.ContentLength.ToString() + newext; //重新为文件命名,时间毫秒部分+文件大小+扩展名
myFile.PostedFile.SaveAs(Server.MapPath(photos + "//" + photoName2)); // 保存文件到路径,用Server.MapPath()取当前文件的绝对目录.在asp.net里"/"必须用""代替
Label1.Text = photos + "//" + photoName2;
}
}
}
注意:在Web.config文件里要加入
<httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="1024000" executionTimeout="900" />
否则大文件上传出错!