var uploadFile = null; var isFileValid = false; function bindInputPictureEvent() { uploadFile = null; isFileValid = false; $('#carSearchImg').unbind().click(function () { $('#fileImage').trigger('click'); }); $("#fileImage").get(0).addEventListener("change", function (e) { var files = e.target.files || e.dataTransfer.files; if (files.length == 0) { return; } uploadFile = files[0]; if (uploadFile) { var reader = new FileReader(); reader.onload = function (e) { var newStr = uploadFile.name.split("").reverse().join(""); var type = newStr.split(".")[0].split("").reverse().join(""); if (uploadFile.type.indexOf("image") == 0) { $('#carSearchImg').attr('src', e.target.result); $('#carSearchImg').blowup({}); $('.upload_message_tip').hide(); //$('#carSearchImg').attr('rel', e.target.result); //$("#carSearchImg").imagezoom(); //$('#bookImageContainer').show(); isFileValid = true; uploadCarSearchImage(uploadFile); } else { isFileValid = false; //$('#bookImageContainer').hide(); $('#alertModal').find('.modal-body p').html('文件类型不符合'); $('#alertModal .btnBox').hide(); $('#alertModal').modal('show'); } } reader.readAsDataURL(uploadFile); } }, false); var uploadCarSearchImage = function (image) { var self = this; var formdata = new FormData(); formdata.append("file", image, encodeURI(image.name)); //formdata.append("bookDetail", $.toJSON(book)); var xhr = new XMLHttpRequest(); // 进度 xhr.upload.addEventListener("progress", function (e) { // 回调到外部 //self.onProgress(image, e.loaded, e.total); }, false); // 完成 xhr.addEventListener("load", function (e) { var response = e.currentTarget.response; var responseObj = JSON.parse(response); console.log(responseObj); var responseStatus = responseObj.status; if (responseStatus == "OK") { var hphm = responseObj.data.plateNum; var plateType = responseObj.data.plateType; var vehicleColor = responseObj.data.vehicleColor; var brandType = responseObj.data.brandType; $('#car_plate').val(hphm); $('#car_type').val(plateType); // 暂时隐藏,赋值之后查询不到一次识别数据 // $('#car_color').val(vehicleColor); // $('#car_brand').val(brandType); // $('#plate_color').val(plateType2ColorMap[plateType]); } uploadFile = null; isFileValid = false; $("#fileImage").val(""); return; }, false); // 错误 xhr.addEventListener("error", function (e) { // 回调到外部 $('#alertModal').find('.modal-body p').html('图片识别失败,请刷新页面重试!'); $('#alertModal .btnBox').hide(); $('#alertModal').modal('show'); }, false); xhr.open("POST", "/car_image/image_data_service/vehicle_image/analyzing_uploading_file", true); //xhr.setRequestHeader("context-type","multipart/form-data;charset=utf-8"); //xhr.setRequestHeader("content-type","application/json"); xhr.send(formdata); } }
http://blog.okbase.net/jquery2000/archive/1296.html