控制器中:
public string addpic(HttpPostedFileBase pic, int ptype)
{
string pfield = ptype == 1 ? "photo" : "photoOfCard";
int length = pic.ContentLength;
if (length > 60 * 1024)
{
return "上传图片请限制在60K";
}
byte[] bb = new byte[length];
pic.InputStream.Read(bb, 0, bb.Length);
if (Session["para"] != null)
{
Hashtable hs = (Hashtable)Session["para"];
string photo = Convert.ToBase64String(bb);
hs[pfield] = photo;
return "ok";
}
else
{
return "请求已超时,请返回上一步继续操作。";
}
}
参数 pic 的名字和html中控件名是一样的。
Html:
<div class="list-group">
<div class="list-group-item active">
<h4 class="list-group-item-heading">
证件照
</h4>
</div>
<div class="list-group-item">
<div class="input-group input-group-sm" style="width:150px;">
<span class="input-group-addon" id="sizing-addon3" style="width: 80px; text-align: right;">证件照:</span>
<span class="input-group-addon" onclick="ptype = 1; $('input[id=pic]').click();" style="cursor:pointer;text-decoration:underline;">选择文件</span>
</div>
</div>
<div class="list-group-item" id="divzj" >
<div class="input-group input-group-sm" style="width:500px;">
<img src="/home/getpic?ptype=1" id="piczj" alt="" />
</div>
</div>
</div>
<div class="list-group">
<div class="list-group-item active">
<h4 class="list-group-item-heading">
身份证
</h4>
</div>
<div class="list-group-item">
<div class="input-group input-group-sm" style="width:150px;">
<span class="input-group-addon" id="sizing-addon3" style="width: 80px; text-align: right;">证件照:</span>
<span class="input-group-addon" onclick="ptype = 2; $('input[id=pic]').click();" style="cursor:pointer;text-decoration:underline;">选择文件</span>
</div>
</div>
<div class="list-group-item" id="divsfz">
<div class="input-group input-group-sm" style="width:500px;">
<img src="/home/getpic?ptype=2" id="picsfz" alt="" />
</div>
</div>
</div>
<input id="pic" name="pic" type="file" style="display:none" accept=".jpg,.jpeg,.bmp,.png" onchange="changefile();">
js:
function changefile()
$.ajaxFileUpload
(
{
url: '/home/addpic', //用于文件上传的服务器端请求地址
secureuri: false, //一般设置为false
fileElementId: 'pic', //文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'json', //返回值类型 一般设置为json
data: { ptype: ptype },
success: function (data, status)
if (data == "ok") {
var img = ptype == 1 ? "piczj" : "picsfz";
$('#' + img).attr('src', '/home/getpic?ptype=' + ptype + '&t=' + (new Date()).valueOf());
}
else {
alert(data);
}
},
error: function (data, status, e)//服务器响应失败处理函数
{
其中:file的change事件一定要在οnchange=”changefile();”中,否则只响应一次。