首先引入 相应的jquery
<script src="script/jquery-1.7.1.min.js"></script>
<script src="script/ajaxfileupload.js"></script>
ajaxFileUpload 使用说明
$.ajaxFileUpload({
url: 'PhotoGet.ashx',//执行上传处理的文件地址
secureuri: false,//是否加密,一般是false,默认值为false
fileElementId: 'UpImg1',//<input type="file" id="UpImg1" name="UpImg1"/> 这里的fileElementId 属性值必须和id是一样的并且要求这个控件要有name属性,用于在服务器端接收
data: {//额外传递的数据,使用json,此时必须设置type为post
type:1
},
type:'post',//请求方式,如果传递额外数据,必须是post
success: function (data){//成功的回调函数,内部处理会加上html标签
//因返回的data 是dom对象需转换成jquery对象才能获取到对应的相对路径
$("#img1").attr("src", $(data).text());
}
});
前段其他代码
<body>
<input type="file" id="UpImg1" name="UpImg1" />
<input type="button" id="btnUpload" value="上传" />
<br/>
<img id="img1" src="" />
</body>
服务器端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebUI
{
/// <summary>
/// PhotoGet 的摘要说明
/// </summary>
public class PhotoGet : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//获取要保存的文件
HttpPostedFile file = context.Request.Files["UpImg1"];
//保存文件的相对文件路径
string path1 = "/loadimg/" + file.FileName;
//把相对文件路径转换成绝对文件路径
string path2 = context.Server.MapPath(path1);
//保存传的文件
file.SaveAs(path2);
//返回保存文件的相对路径
context.Response.Write(path1);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}