先看效果图:
文件布局:
defualt.aspx代码:
<head runat="server">
<title></title>
<script src="script/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="script/jquery.form.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<table width="600">
<tr>
<td style="width: 150px; text-align: right;">
用户名:
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 150px; text-align: right;">
图片名称:
</td>
<td>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 150px; text-align: right;">
图片:
</td>
<td>
<asp:HiddenField ID="ImageHideFile" runat="server" />
<div id="dvi" style="clear: both; margin-bottom: 5px;">
</div>
<span id="filespan">
<input type="file" name="file" id="FileUpload" />
</span>
<input id="UploadButton" type="button" value="upload" />
</td>
</tr>
<tr>
<td colspan="2" style="padding-left: 160px">
<asp:Button ID="Button4" runat="server" Text="Submit" OnClick="Button2_Click" />
</td>
</tr>
</table>
</form>
<script src="script/JScript.js" type="text/javascript"></script>
</body>
default.aspx后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
webpublic wp = new webpublic();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
wp.ShowMessageBox(ImageHideFile.Value);
//wp.Show_Msg(ImageHideFile.Value);
}
}
webpublic.cs主要代码:
/// <summary>
/// 页面只弹出消息框,不跳转,不刷新!
/// </summary>
/// <param name="msg"></param>
public void ShowMessageBox(string msg)
{
Page page = (Page)HttpContext.Current.CurrentHandler;
page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + msg + "')</script>");
}
/// <summary>
/// 验证文件类型
/// </summary>
/// <param name="file">上传上来的文件</param>
/// <returns></returns>
public Boolean IsAllowedExtension(HttpPostedFile file)
{
int fileLen = file.ContentLength;
byte[] imgArray = new byte[fileLen];
file.InputStream.Read(imgArray, 0, fileLen);
MemoryStream ms = new MemoryStream(imgArray);
System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
string fileclass = "";
byte buffer;
try
{
buffer = br.ReadByte();
fileclass = buffer.ToString();
buffer = br.ReadByte();
fileclass += buffer.ToString();
}
catch
{
}
finally
{
br.Close();
ms.Close();
}
//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677" || fileclass == "13780")
return true;
else
return false;
}
// <summary>
/// 提示成功信息!.back()
/// </summary>
/// <param name="msg"></param>
/// <param name="url"></param>
public void Show_Msg(string msg)
{
HttpContext.Current.Response.Write("<script>alert(\"" + msg + "\");history.back();</script>");
HttpContext.Current.Response.End();
}
fileupload.aspx的后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class WebAdmin_fileupload : System.Web.UI.Page
{
webpublic wp = new webpublic();
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files["file"] != null)
{
HttpPostedFile file = Request.Files["file"];
//验证文件格式
if (wp.IsAllowedExtension(file))
{
Random ra = new Random();
String filePath = "~/Files/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ra.Next(1000, 9999)
//获取文件后缀
+ System.IO.Path.GetExtension(file.FileName);
try
{
file.SaveAs(Server.MapPath(filePath));
Response.Write(ResolveUrl(filePath));
}
catch (Exception)
{
Response.Write("文件上传发生错误!");
}
}
else
{
Response.Write("文件格式不正确!");
}
}
if (Request["myurl"] != null)
{
var url =Request["myurl"];
try
{
System.IO.File.Delete(Server.MapPath(url));
Response.Write("文件删除成功!");
}
catch (Exception)
{
Response.Write("文件删除失败!");
}
}
Response.End();
}
}
js代码部分:
$(document).ready(function() {
var img = document.createElement("img");
img.title = "双击图片可删除图片";
img.id = "UploadImg";
img.height = "100";
$("#UploadButton").click(function() {
if ($("#FileUpload").val() == "") {
alert("请选择要上传的图片!");
return false;
}
//如果已有图片,则先把图片删除
if ($("#ImageHideFile").val() != "") {
$.get("fileupload.aspx?myurl=" + $("#ImageHideFile").val(),
function(data) {
$("#ImageHideFile").val("");
$("#UploadImg").attr("src", "");
});
}
var myform = document.createElement("form");
myform.action = "fileupload.aspx";
myform.method = "post";
myform.enctype = "multipart/form-data";
document.body.appendChild(myform); //创建表单后一定要加上这句否则得到的form不能上传。 //document后要加上body,否则火狐下不行。
var form = $(myform);
var fu = $("#FileUpload").clone(true).val("");
var fua = $("#FileUpload").appendTo(form);
$("#filespan").html("<img src=\"images/loading.gif\" /> 正在上传.. ");
form.ajaxSubmit({
success: function(data) {
if (data == "文件上传发生错误!" || data == "文件格式不正确!") {
alert(data);
}
else {
$("#ImageHideFile").val(data);
$("#dvi").find("img").remove();
$("#dvi").append($(img));//要先append再给img赋值,否则在ie下不能缩小宽度
$(img).attr("src", data);
//绑定图片双击事件。实现双击图片删除图片
$(img).bind("dblclick",
function() {
if ($("#ImageHideFile").val() == "") {
return;
}
$.get(
"fileupload.aspx?myurl=" + $("#ImageHideFile").val(),
function(data) {
alert(data);
if (data == "文件删除成功!") {
$("#ImageHideFile").val("");
$(img).remove();
}
$("#UploadImg").attr("src", $("#ImageHideFile").val());
});
});
}
$("#filespan").html(fu);
form.remove();
}
});
});
});
每次只能上传一张图片。每次上传时如果已经有图片则把原图删除再上传,上传后双击图片可删除图片。适合用于只上传一张图片。
引用了这两个类库
<script src="script/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="script/jquery.form.js" type="text/javascript"></script>
2011年9月13日 改进版本请看:http://blog.youkuaiyun.com/weizengxun/article/details/6769977