调用手机摄像头并上传图片--jquery ajax
1、图片框样式与进度条样式
.alert_img_content { width: 44%; float: left; margin: 3%; border: 1px solid #ddd; background: url(/Content/images/jiahao.png) no-repeat 50%; position: relative; box-sizing: border-box; }
.alert_img_content input { display: block; height: 100%; width: 100%; opacity: 0; position: absolute; top: 0; left: 0; z-index: 2; }
.alert_img_content img { display: block; height: 100%; width: 100%; position: absolute; top: 0; left: 0; z-index: 1; }
.alert_img_content a { display: block; text-align: right; padding-right: 7px; padding-top: 2px; font-size: 20px; box-sizing: border-box; border-bottom-left-radius: 100%; height: 40px; width: 40px; background-color: red; color: #fff; /* line-height: 23px; */ position: absolute; top: 0; right: 0; z-index: 3; }
.clearfix:after { content: ""; display: block; height: 0; clear: both; visibility: hidden; }
.progress-bar { background-color: #666; width: 100%; text-align: center; position: relative; height: 20px; line-height: 20px; border-radius: 10px; }
.progress-bar-font { width: 100%; color: #fff; position: absolute; z-index: 3; }
.progress-bar-plan { background-color: red; position: absolute; height: 20px; width: 0%; border-radius: 10px; transition: 0.3s; }
2、图片标签
<div class="alert_img_box clearfix"> <div class="alert_img_content"> <input type="file" accept="image/*" capture="camera" onchange="inputChange(this)"> <img /> <a style="display: none;" onclick="deletePic(this)">×</a> </div> </div>
3、进度条标签
<div class="progress-bar" style="display: none;"> <div class="progress-bar-plan"></div> <div class="progress-bar-font"> 0% </div> </div>
4、file绑定的方法
function inputChange(obj) { var picList = $(".alert_img_content"); var pic = picList.eq(picList.length - 1); if (pic.find("input").val() != "" && picList.length < 5) { $(".alert_img_box").append(html); calcHeight(); } if ($(obj).val() != "") { $(obj).parent().find("a").show(); } //设置显示图片 function getObjectURL(file) { var url = null; if (window.createObjcectURL != undefined) { url = window.createOjcectURL(file); } else if (window.URL != undefined) { url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { url = window.webkitURL.createObjectURL(file); } return url; } var objURL = getObjectURL(obj.files[0]); $(obj).parent().find("img").attr("src", objURL); }
5、删除代码
function deletePic(obj)
{
var len = $(".alert_img_content").length;
var pic = $(".alert_img_content").eq(len - 1);
$(obj).parent().remove();
if (len == 5 && pic.find("input").val() != "")
{
$(".alert_img_box").append(html);
calcHeight();
}
}
6、保持图片框为正方形的代码
function calcHeight()
{
var obj = $(".alert_img_box .alert_img_content");
obj.height(obj.width());
}
7、上传的js代码
function saveDealinfo() { $("#btn_save").click(function () { var formData = new FormData(); if ($("input[type=\'file\']").length > 1) { $(".progress-bar").show(); $(".progress-bar-plan").css("background-color", "red"); $("input[type=\'file\']").each(function (index, item) { formData.append("file", $("input[type=\'file\']")[index].files[0]); }) } formData.append("alarmID", "@Model.Item1.AlarmID"); formData.append("remark", $("textarea[name=remark]").val()); formData.append("alarmStatus", $("input[name=alarmDealStatus]:checked").val()) formData.append("alarmConfirm", $("input[name=alarmConfim]:checked").val()) //首先封装一个方法 传入一个监听函数 返回一个绑定了监听函数的XMLHttpRequest对象 var xhrOnProgress = function (fun) { xhrOnProgress.onprogress = fun; //绑定监听 //使用闭包实现监听绑 return function () { //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象 var xhr = $.ajaxSettings.xhr(); //判断监听函数是否为函数 if (typeof xhrOnProgress.onprogress !== \'function\') return xhr; //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去 if (xhrOnProgress.onprogress && xhr.upload) { xhr.upload.onprogress = xhrOnProgress.onprogress; } return xhr; } } $.ajax({ url: "/Interface/DealAlarm", type: \'POST\', data: formData, // 告诉jQuery不要去处理发送的数据 processData: false, // 告诉jQuery不要去设置Content-Type请求头 contentType: false, //beforeSend: function () //{ // console.log("正在进行,请稍候"); //}, xhr: xhrOnProgress(function (evt) { var percent = Math.floor(evt.loaded / evt.total * 100);//计算百分比 $(".progress-bar-plan").css("width", percent + "%"); $(".progress-bar-font").html(percent + \'%\'); if (percent == 100) { $(".progress-bar-plan").css("background-color", "#0bae27"); } ////console.log(percent); //// 设置进度条样式 //$(\'#jdt\').css(\'width\',percent * 3 + \'px\'); //$(\'#jdt\').css(\'background\',\'skyblue\'); ////显示进度百分比 //$(\'#jdt\').text(percent+\'%\'); //$(\'#loaded\').text(evt.loaded/1024 + \'K\'); //$(\'#total\').text(evt.total/1024 + \'K\'); }), success: function (response) { if (response.Code == 0) { } else { } }, error: function (responseStr) { console.log("error"); } }); }) }
8、mvc的接收代码
public string DealAlarm() { ResponseResult<string> response = new ResponseResult<string>(); long alarmID = Convert.ToInt64(Request["alarmID"]); string remark = Convert.ToString(Request["remark"]); int alarmStatus = Convert.ToInt32(Request["alarmStatus"]); int alarmConfirm = Convert.ToInt32(Request["alarmConfirm"]); List<string> urlList = new List<string>(); IResult iRst = SaveImage(urlList);
return string.empty;
}
8、图片保存代码
public IResult SaveImage(List<string> urlList) { try { HttpFileCollectionBase coll = Request.Files; HttpPostedFileBase file; string domain = "//" + Request.Url.Host + (Request.Url.Port == 0 ? "" : ":" + Request.Url.Port.ToString()) + "/Content/"; for (int i = 0; i < coll.Count; i++) { file = coll[i]; if (string.IsNullOrEmpty(file.FileName)) { continue; } if (file.ContentLength == 0) { continue; } string pictureName = DateTime.Now.ToString("yyyyMMddHHmmssfff"); string extension = Path.GetExtension(file.FileName); string folder = DateTime.Now.ToString("yyyyMM"); string path = PhotoUrl + "Upload\\" + folder + @"\" + pictureName + extension; if (!Directory.Exists(PhotoUrl + folder)) { Directory.CreateDirectory(PhotoUrl + "Upload\\" + folder); } file.SaveAs(path); urlList.Add(domain + folder + @"/" + pictureName + extension); } return IResult.Success; } catch (Exception ex) { Logging.Logger.Error(ex); return IResult.UnknownErr; } }