控制器中:
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">
class="list-group-item-heading">
证件照
div>
<div class="list-group-item">
<div class="input-group input-group-sm" style="width:150px;">
class="input-group-addon" id="sizing-addon3" style="width: 80px; text-align: right;">证件照:
class="input-group-addon" onclick="ptype = 1; $('input[id=pic]').click();" style="cursor:pointer;text-decoration:underline;">选择文件
div>
div>
<div class="list-group-item" id="divzj" >
<div class="input-group input-group-sm" style="width:500px;">
"/home/getpic?ptype=1" id="piczj" alt="" />
div>
div>
div>
<div class="list-group">
<div class="list-group-item active">
class="list-group-item-heading">
身份证
div>
<div class="list-group-item">
<div class="input-group input-group-sm" style="width:150px;">
class="input-group-addon" id="sizing-addon3" style="width: 80px; text-align: right;">证件照:
class="input-group-addon" onclick="ptype = 2; $('input[id=pic]').click();" style="cursor:pointer;text-decoration:underline;">选择文件
div>
div>
<div class="list-group-item" id="divsfz">
<div class="input-group input-group-sm" style="width:500px;">
"/home/getpic?ptype=2" id="picsfz" alt="" />
div>
div>
div>
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,
fileElementId: 'pic',
dataType: '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)//服务器响应失败处理函数
{
alert(e);
}
}
)
}
其中:file的change事件一定要在onchange=”changefile();”中,否则只响应一次。