PhoneGap+JQM实现用手机拍照并且上传图片的例子10th of September 2012 最近公司在做一个移动版的产品,是基于PhoneGap2.0和JQM1.1.1的开发的。今天在整一个用手机拍照然后上传图片的功能,整整做了一天,没有一天成果,只能实现图片拍照并存储在手机里而已,一直没能实现图片上传的功能。也尝试了从网上搜到的一大堆的例子,均无果,最后近乎崩溃了。 在下午5点多的时候,和公司的一位技术大牛一起探讨,通过各种调试及尝试之后,终于完美地实现了基于PhoneGap+JQM实现手机拍照并且上传图片的功能,现在在这里做好总结备份,并分享给广大需要的同仁们!需要的文件在一起打包了,或者可以自己上网找。 首先是拍照功能: 具体参数请移步到PhoneGap的官网API http://docs./en/2.0.0/cordova_camera_camera.md.html#Camera 接着是图片(文件)上传功能: 具体参数请移步到PhoneGap的官网API,主要是FileTransfer这个 http://docs./en/2.0.0/cordova_file_file.md.html#FileTransfer 废话不多说,贴上源码,由于是公司项目,只能贴上改动过的源码。但具体思路还是能够表达的。 网页文件的部分源码: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="jslib/jqm1.1/jquery.mobile-1.1.1.css" /> <script src="jslib/phoneGap/cordova-2.0.0.js"></script> <script src="jslib/jqm1.1/jquery-1.7.1.js"></script> <script src="jslib/jqm1.1/jquery.mobile-1.1.1.js"></script> <script src="jslib/phoneGap/phonegap2.0.js"></script> <script type="text/javascript" src="js/main.js"></script><link rel="stylesheet" href="third/mobiscroll-2.0.2/css/mobiscroll-2.0.2.custom.min.css"></link> <script type="text/javascript" src="third/mobiscroll-2.0.2/js/mobiscroll-2.0.2.custom.min.js"></script> <script type="text/javascript"> $(document).bind("mobileinit", function() { //$.mobile.autoInitialize = false; //删除这行配置参数就会出现渲染错误 $.support.cors = true; $.mobile.allowCrossDomainPages = true; }); var pictureSource; // picture source var destinationType; // sets the format of returned value // Wait for Cordova to connect with the device // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready to be used! // function onDeviceReady() { pictureSource = navigator.camera.PictureSourceType; destinationType = navigator.camera.DestinationType; } // Called when a photo is successfully retrieved // function onPhotoDataSuccess(imageData) { // Uncomment to view the base64 encoded image data // console.log(imageData); // Get image handle // var smallImage = document.getElementById('smallImage'); // Unhide image elements // smallImage.style.display = 'block'; // Show the captured photo // The inline CSS rules are used to resize the image // //smallImage.src = "data:image/jpeg;base64," + imageData; smallImage.src = imageData; } // Called when a photo is successfully retrieved // function onPhotoURISuccess(imageURI) { // Uncomment to view the image file URI // console.log(imageURI); // Get image handle // var largeImage = document.getElementById('largeImage'); // Unhide image elements // largeImage.style.display = 'block'; // Show the captured photo // The inline CSS rules are used to resize the image // //largeImage.src = "data:image/jpeg;base64," + imageData; largeImage.src = imageURI; } // A button will call this function // function capturePhoto() { // Take picture using device camera and retrieve image as base64-encoded string navigator.camera.getPicture(uploadPhoto, onFail, { quality : 50, destinationType : navigator.camera.DestinationType.FILE_URI,//这里要用FILE_URI,才会返回文件的URI地址 //destinationType : Camera.DestinationType.DATA_URL, sourceType : Camera.PictureSourceType.CAMERA, allowEdit : true, encodingType : Camera.EncodingType.JPEG, popoverOptions : CameraPopoverOptions, saveToPhotoAlbum : true }); } // A button will call this function // function capturePhotoEdit() { // Take picture using device camera, allow edit, and retrieve image as base64-encoded string navigator.camera.getPicture(uploadPhoto, onFail, { quality : 50, allowEdit : true, destinationType : destinationType.DATA_URL, saveToPhotoAlbum : true }); } // A button will call this function // function getPhoto(source) { // Retrieve image file location from specified source navigator.camera.getPicture(uploadPhoto, onFail, { quality : 50, destinationType : destinationType.FILE_URI,//这里要用FILE_URI,才会返回文件的URI地址 sourceType : source }); } // Called if something bad happens. // function onFail(message) { alert('Failed because: ' + message); } function uploadPhoto(imageURI) { var options = new FileUploadOptions(); options.fileKey = "fileAddPic";//用于设置参数,对应form表单里控件的name属性,这是关键,废了一天时间,完全是因为这里,这里的参数名字,和表单提交的form对应 options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1); //如果是图片格式,就用image/jpeg,其他文件格式上官网查API options.mimeType = "image/jpeg"; options.mimeType = "multipart/form-data";//这两个参数修改了,后台就跟普通表单页面post上传一样 enctype="multipart/form-data" //这里的uri根据自己的需求设定,是一个接收上传图片的地址 var uri = encodeURI(CONSTANT['context'] + "/user/publish/ajaxUploadPic"); //alert(imageURI); //alert(uri); options.chunkedMode = false; /* var params = new Object(); params.fileAddPic = imageURI; options.params = params; */ var ft = new FileTransfer(); ft.upload(imageURI, uri, win, fail, options); } function win(r) { alert("上传成功"); var response = r.response; //alert("response = " + response); //这里的message是自定义的返回值,具体的根据自己的需求而定 var message = eval("(" + r.response + ")").message; $("#_picFile").val(message); //alert("message = " + message); var imageURI = CONSTANT['context'] + message; //alert("imageURI =" + imageURI); onPhotoDataSuccess(imageURI); onPhotoURISuccess(imageURI); //alert("Code = " + r.responseCode); //alert("Response = " + r.response); //alert("Sent = " + r.bytesSent); //以下是三个默认的返回参数 console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); } function fail(error) { alert("An error has occurred: Code = " + error.code); alert("upload error source " + error.source); alert("upload error target " + error.target); console.log("upload error source " + error.source); console.log("upload error target " + error.target); } </script> </head> <body> <!-- page write --> <div data-role="page" id="write"> <div data-role="header" data-position="fixed"> <a href="#" data-icon="back" data-rel="back">返回</a> <h1>拍照并上传图片</h1> <a href="javascript:void(0);" data-icon="arrow-l" id="btn_nowsend">设置</a> </div> <!-- /header --> <div data-role="content"> <input id="_picFile" type="hidden" value="" /> <!-- take photoes --> <button onclick="capturePhoto();">点击拍照</button> <br> <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">从相册选择图片</button> <br> <button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">从相册选择图片</button> <br> <img style="display:none;width:120px;height:120px;" id="smallImage" src="" /> <img style="display:none;width:240px;height:240px;" id="largeImage" src="" /> </div> <!-- /content --> <div data-role="footer" data-position="fixed" class="ui-bar"> <a id="btn_timingsend" href="javascript:void(0);" data-role="button" data-icon="plus">底部菜单</a> <a href="javascript:void(0);" data-role="button" data-icon="arrow-u">底部菜单</a> </div> <!-- /footer --> </div> <!-- /page write --> </body> </html> 后台文件的部分源码: 后台整体框架用的是Spring MVC,这里就给出调用图片上传的方法头 @RequestMapping(value = "user/publish/ajaxUploadPic", method = RequestMethod.POST) public @ResponseBody ModelAndView ajaxUploadPic(@RequestParam("fileAddPic") final CommonsMultipartFile fileData, final HttpServletResponse response) { //@RequestParam("fileAddPic")这个其实就是上面的网页文件里的options.fileKey = "fileAddPic"这个参数,其实如果是用浏览器页面的表单进行图片上传,则要求表单控件的name属性为fileAddPic,具体的可以自己设定。 这里就有点疑惑了,如果是多图片或者多文件上传,参数应该怎么设置呢?难道是循环的上传,每次一个文件麽!不明白设计者的思路。不过还是可以用,经过真机测试,绝对可行。 这里就已经实现了文件流的传输了。接着具体如何将文件保存到具体位置,请各位大神自己动手了。 小弟在这里就抛砖引玉了。 } 作者:被梦想绊倒的小马 QQ:395487290 新浪微博:http://weibo.com/u/2055506953 欢迎交流沟通! |
|
来自: liuguichuan > 《Android》