1:首先引入脚本jquery.js和 ajaxfileupload.js
2:测试布局:
<div>
<form>
<input type="file" name="file1" id="file1" />
<input type="text" name="txt" id="txt" />
<input type="text" name="pwd" id="pwd"/>
<input type="button" value="上传" />
</form>
<p><img id="img1" alt="" src="" /></p>
</div>
3:jq代码:
$(function () {
$(":button").click(function () {
var pic = $("#file1").val();
if (pic.length > 0) {
var subStr = pic.substr(pic.lastIndexOf('.') + 1);//截取字符串
if (subStr == "jpg" || subStr == "png" || subStr == "gif" || subStr == "jpeg ") {//判断文件类型
upload();
} else {
alert("请选择正确的文件类型");
return;
}
} else {
alert("请选择图片");
return;
}
});
})
function upload() {
$.ajaxFileUpload({
url: '../../Home/Upload',
data:{txt:txt,pwd:pwd},
secureuri: false, //一般设置为false
fileElementId: 'file1', //文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'HTML', //返回值类型 一般设置为json
success: function (data,status) {
alert(data);
$("#img1").attr("src", "../../Images/"+data);
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
alert(data.msg);
}
}
}, error: function (error) {
alert("错误");
}
});
}
</script>
4:后台代码:
public ActionResult Upload() {
NameValueCollection nv = System.Web.HttpContext.Current.Request.Form;//获取传过来的参数data的值
HttpFileCollection hc = System.Web.HttpContext.Current.Request.Files;//获取前台控件file
string txt = nv.Get("txt");//得到值
string pwd = nv.Get("pwd");
string imgPath = "";//用于存储路径
string PIC = hc[0].FileName;//图片名
string substr = "";//保存截取的字符
string picsrc = "";//返回的图片路径
if (hc.Count > 0)
{
//用ie上传图片时会带出图片的绝对路径,我们只需判断该字符串的是否有盘符路径,有的话截取路径
if (PIC.Contains("C:")||PIC.Contains("D:")||PIC.Contains("E:")||PIC.Contains("F:")||PIC.Contains("G:"))//判断字符串中是否有盘符路径
{
substr = PIC.Substring(PIC.LastIndexOf('\\')+1);
imgPath = "~/Images/" + substr;
picsrc = substr;
}
else
{
picsrc = PIC;
imgPath = "~/Images/" + PIC;
}
string mapth = Server.MapPath(imgPath);
hc[0].SaveAs(mapth);
}
return Content(picsrc);
}