ncowboy

导航

asp.net上传文件图片的做法

新建一个web项目。把我下面贴的两个文件拿进去覆盖同名文件
webform1.aspx内,<>已经被替换为<>。请自己再替换回来。

webform1.aspx
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication3.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="javascript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body ms_positioning="GridLayout">
<form id="Form1" method="post" runat="server">
<FONT face="宋体"></FONT><INPUT id="File1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 8px" type="file"
name="File1" runat="server">
<asp:Label id="Label1" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 40px" runat="server">Label</asp:Label>  
<INPUT style="Z-INDEX: 103; LEFT: 256px; POSITION: absolute; TOP: 8px" type="submit" value="Submit">
<asp:Image id="Image1" style="Z-INDEX: 104; LEFT: 32px; POSITION: absolute; TOP: 88px" runat="server"></asp:Image>
</form>
</FONT>
</body>
</HTML>

WebForm1.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication3
{
///


/// Summary description for WebForm1.
///

public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Image Image1;
protected System.Web.UI.HtmlControls.HtmlInputFile File1;

private void Page_Load(object sender, System.EventArgs e)
{
if(this.IsPostBack){
try
{
string filename=Server.MapPath("./")+"UpLoadFiles/"+Guid.NewGuid().ToString();
this.File1.PostedFile.SaveAs(filename);
this.Label1.Text=filename;
this.Image1.ImageUrl=filename;
}
catch(Exception ee)
{
this.Label1.Text=ee.Message;
}
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

///


/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
}

posted on 2004-02-05 13:35  35号房客  阅读(2662)  评论(0)    收藏  举报