1 使用标準HTML來進行圖檔上傳
前台代碼:
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2" style="height: 21px" >
使用标準HTML來進行圖檔上傳</td>
</tr>
<td style="width: 400px">
<input id="InputFile" style="width: 399px" type="file" runat="server" /></td>
<td style="width: 80px">
<asp:Button ID="UploadButton" runat="server" Text="上傳圖檔" OnClick="UploadButton_Click" /></td>
<td colspan="2" >
<asp:Label ID="Lb_Info" runat="server" ForeColor="Red"></asp:Label></td>
</table>
</div>
</form>
</body>
背景代碼:
using System;
using System.Data;
using System.Configuration;
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadButton_Click(object sender, EventArgs e)
string uploadName = InputFile.Value;//擷取待上傳圖檔的完整路徑,包括檔案名
//string uploadName = InputFile.PostedFile.FileName;
string pictureName = "";//上傳後的圖檔名,以目前時間為檔案名,確定檔案名沒有重複
if (InputFile.Value != "")
{
int idx = uploadName.LastIndexOf(".");
string suffix = uploadName.Substring(idx);//獲得上傳的圖檔的字尾名
pictureName = DateTime.Now.Ticks.ToString() + suffix;
}
try
if (uploadName != "")
{
string path = Server.MapPath("~/images/");
InputFile.PostedFile.SaveAs(path + pictureName);
}
catch (Exception ex)
Response.Write(ex);
}

2 單檔案上傳
這是最基本的檔案上傳,在asp.net1.x中沒有這個FileUpload控件,隻有html的上傳控件,那時候要把html控件轉化為伺服器控件,
很不好用。其實所有檔案上傳的美麗效果都是從這個FileUpload控件衍生,第一個例子雖然簡單卻是根本。
<table style="width: 90%">
<td style="width: 159px" colspan=2>
<strong><span style="font-size: 10pt">最簡單的單檔案上傳</span></strong></td>
<td style="width: 600px">
<asp:FileUpload ID="FileUpload1" runat="server" Width="600px" /></td>
<td align=left>
<asp:Button ID="FileUpload_Button" runat="server" Text="上傳圖檔" OnClick="FileUpload_Button_Click" /></td>
<td colspan=2>
<asp:Label ID="Upload_info" runat="server" ForeColor="Red" Width="767px"></asp:Label></td>
protected void FileUpload_Button_Click(object sender, EventArgs e)
if (FileUpload1.PostedFile.FileName == "")
//if (FileUpload1.FileName == "")
//if (!FileUpload1.HasFile) //擷取一個值,該值訓示 System.Web.UI.WebControls.FileUpload 控件是否包含檔案。包含檔案,則為 true;否則為 false。
this.Upload_info.Text = "請選擇上傳檔案!";
else
string filepath = FileUpload1.PostedFile.FileName; //得到的是檔案的完整路徑,包括檔案名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg
//string filepath = FileUpload1.FileName; //得到上傳的檔案名20022775_m.jpg
string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg
string serverpath = Server.MapPath("~/images/") + filename;//取得檔案在伺服器上儲存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg
FileUpload1.PostedFile.SaveAs(serverpath);//将上傳的檔案另存為
this.Upload_info.Text = "上傳成功!";
this.Upload_info.Text = "上傳發生錯誤!原因是:" + ex.ToString();
3 多檔案上傳
<table style="width: 343px">
<td style="width: 100px">
多檔案上傳</td>
</td>
<asp:FileUpload ID="FileUpload1" runat="server" Width="475px" />
</td>
<asp:FileUpload ID="FileUpload2" runat="server" Width="475px" /></td>
<asp:FileUpload ID="FileUpload3" runat="server" Width="475px" /></td>
<asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="一起上傳" />
<asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="448px"></asp:Label></td>
</table>
背景代碼:
protected void bt_upload_Click(object sender, EventArgs e)
if (FileUpload1.PostedFile.FileName == "" && FileUpload2.PostedFile.FileName == "" && FileUpload3.PostedFile.FileName == "")
this.lb_info.Text = "請選擇檔案!";
else
HttpFileCollection myfiles = Request.Files;
for (int i = 0; i < myfiles.Count; i++)
HttpPostedFile mypost = myfiles[i];
try
{
if (mypost.ContentLength > 0)
{
string filepath = mypost.FileName;//C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg
string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg
string serverpath = Server.MapPath("~/images/") + filename;//C:\Inetpub\wwwroot\WebSite2\images\20022775_m.jpg
mypost.SaveAs(serverpath);
this.lb_info.Text = "上傳成功!";
}
}
catch (Exception ex)
this.lb_info.Text = "上傳發生錯誤!原因:" + ex.Message.ToString();
4 用戶端檢查上傳檔案類型(以上傳圖檔為例)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<script language="javascript">
function Check_FileType()
var str=document.getElementById("FileUpload1").value;
var pos=str.lastIndexOf(".");
var lastname=str.substring(pos,str.length);
if(lastname.toLowerCase()!=".jpg"&&lastname.toLowerCase()!=".gif")
alert("您上傳的檔案類型為"+lastname+",圖檔必須為.jpg,.gif類型");
return false;
return true;
}
</script>
</head>
<td colspan="2">
用戶端檢查上傳檔案類型</td>
<td style="width: 444px">
<asp:FileUpload ID="FileUpload1" runat="server" Width="432px" /></td>
<asp:Button ID="bt_upload" runat="server" Text="上傳圖檔" OnClick="bt_upload_Click" OnClientClick="return Check_FileType()" /></td>
<td colspan="2" style="height: 21px">
<asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="515px"></asp:Label></td>
</body>
</html>
注意:點選上傳時先觸發用戶端事件OnClientClick="return Check_FileType()"
this.lb_info.Text = "請選擇檔案!";
string filepath = FileUpload1.PostedFile.FileName;
//if (!IsAllowedExtension(FileUpload1))
//{
// this.lb_info.Text = "上傳檔案格式不正确!";
//}
if (IsAllowedExtension(FileUpload1) == true)
string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
string serverpath = Server.MapPath("~/images/") + filename;
FileUpload1.PostedFile.SaveAs(serverpath);
this.lb_info.Text = "上傳成功!";
else
this.lb_info.Text = "請上傳圖檔!";
this.lb_info.Text = "上傳發生錯誤!原因:" + ex.ToString();
private static bool IsAllowedExtension(FileUpload upfile)
string strOldFilePath = "";
string strExtension="";
string[] arrExtension ={ ".gif", ".jpg", ".bmp", ".png" };
if (upfile.PostedFile.FileName != string.Empty)
strOldFilePath = upfile.PostedFile.FileName;//獲得檔案的完整路徑名
strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));//獲得檔案的擴充名,如:.jpg
for (int i = 0; i < arrExtension.Length; i++)
if (strExtension.Equals(arrExtension[i]))
return true;
return false;
注意:若去掉用戶端的腳本和用戶端事件OnClientClick="return Check_FileType()",在背景代碼
改為:
if (!IsAllowedExtension(FileUpload1))
this.lb_info.Text = "上傳檔案格式不正确!";
else if (IsAllowedExtension(FileUpload1) == true)
即變成伺服器端檢查上傳檔案類型。
5 伺服器端檢查上傳檔案的類型(檔案内部真正的格式)
伺服器檢查上傳檔案類型</td>
<asp:Button ID="bt_upload" runat="server" Text="上傳圖檔" OnClick="bt_upload_Click" /></td>
using System.IO;
string serverpath = Server.MapPath("images/") + filename;
this.lb_info.Text = "請上傳圖檔";
catch (Exception error)
this.lb_info.Text = "上傳發生錯誤!原因:" + error.ToString();
FileStream fs = new FileStream(upfile.PostedFile.FileName, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
string fileclass = "";
byte buffer;
buffer = r.ReadByte();
fileclass = buffer.ToString();
fileclass += buffer.ToString();
catch
{
r.Close();
fs.Close();
if (fileclass == "255216" || fileclass == "7173"||fileclass=="6677"||fileclass=="13780")//說明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
作者:
Tyler Ning出處:
http://www.cnblogs.com/tylerdonet/本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,如有問題,可以通過以下郵箱位址
[email protected]聯系我,非常感謝。