首先引入 相应的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 ,此方法传递原js文件中不支持此功能,需要在原js文件中增加代码
name:'123',
id:'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;
}
}
}
}
createUploadForm: function(id, fileElementId,data){
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
//...中间省略
/* 为新增部分,支持添加data参数
if(data){
for(var i in data){
$('<input type="hidden" name="'+i+'" value="'+data[i]+'"/>').appendTo(form);
}
} */
return form;
}
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = s.fileElementId;
var form = jQuery.createUploadForm(id, s.fileElementId,s.data);
MVC中服务器端获取data传递的参数
public ActionResult AjaxUpLoadImage()
{
HttpPostedFileBase file = Request.Files["imgUp"];
NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form;
string fileName=Path.GetFileName(file.FileName);
string fileExt=Path.GetExtension(fileName);
if (fileExt == ".jpg")
{
string dir = "/image/";
Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(dir)));
//这里接收用户名称来确定图片的名称
string newfileName = nvc.Get("hfName");
//string newfileName = Guid.NewGuid().ToString();
string fullPath = dir + newfileName + fileExt;
file.SaveAs(Request.MapPath(fullPath));
return Content("ok:" + fullPath);
}
else
return Content("no:文件类型错误");
}