日期:2014-05-17 浏览次数:21109 次
1、使用FileUpload控件
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Study_FileUpload1.aspx.cs" Inherits="StudyFromNow.Study_FileUpload1" %>
<!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>上传-FileUpload</title>
</head>
<body>
<form id="Form1" runat="server">
<div>
<fieldset style="width: 290px">
<legend>FileUpload控件</legend>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="BtnUpload" runat="server" Text="上传" OnClick="BtnUpload_Click" />
<hr />
<asp:Label ID="lblMsg" runat="server" ForeColor="red" /><br />
<asp:Label ID="lblMsg2" runat="server" />
</fieldset>
</div>
</form>
</body>
</html>
?
?
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace StudyFromNow
{
public partial class Study_FileUpload1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnUpload_Click(object sender, EventArgs e)
{
bool isAllowed = false;
string destPath = Server.MapPath("~/Temp/");
if (FileUpload1.HasFile)
{
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".bmp", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
isAllowed = true;
}
}
}
if (isAllowed)
{
try
{
FileUpload1.SaveAs(destPath + FileUpload1.FileName);
lblMsg.Text = "文件上传成功.";
lblMsg2.Text = "<b>原文件路径:</b>" + FileUpload1.PostedFile.FileName + "<br />" +
"<b>文件大小:</b>" + FileUpload1.PostedFile.ContentLength + "字节<br />" +
"<b>文件类型:</b>" + FileUpload1.PostedFile.ContentType + "<br />";
}
catch (Exception ex)
{
lblMsg.Text = "文件上传不成功.";
}
}
else
{
lblMsg.Text = "只能够上传图片文件.";
}
}
}
}
?
?
2、使用 input? type="file"
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Study_FileUpload2.aspx.cs"
Inherits="StudyFromNow.Study_FileUpload2" %>
<!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>文件上传-INPUT</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset>
<legend>文件上传-INPUT</legend>
<input type="file" id="UploadFile" name="UploadFile" runat="server" />
<br />