返回 导航

Cordova

hangge.com

Cordova - 从相册中选择照片并上传,以及拍照上传

作者:hangge | 2016-05-24 09:10
1,安装需要的插件
不管是从相册中选择图片上传,还是拍照上传。我们都需要如下先安装如下三个插件:Camera(相机)、file(文件访问操作)、fileTransfer(文件传输)。
如果没有安装的话,先安装下:
cordova plugin add cordova-plugin-camera
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-transfer

2,选择设备照片并上传 
下面代码样例,点击按钮后会打开系统相册来选择照片,选中的照片会显示在页面上。同时会把选择的照片上传到服务器。
注意camera 插件除了可以选择图片外,也可以选择视频。如果需要实现选择视频功能,我们只要在 getPicture 方法最后一个参数对象中添加 mediaType:navigator.camera.MediaType.VIDEO 配置即可。
               
<!DOCTYPE html>
<html>
    <head>
        <title>Capture Photo</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">
            var pictureSource;
            var destinationType;

            document.addEventListener("deviceready",onDeviceReady,false);

            //Cordova加载完成会触发
            function onDeviceReady() {
                pictureSource=navigator.camera.PictureSourceType;
                destinationType=navigator.camera.DestinationType;
            }

            //获取照片
            function getPhoto(source) {
                //quality : 图像的质量,范围是[0,100]
                navigator.camera.getPicture(onPhotoURISuccess,
                  function(error){console.log("照片获取失败!")},
                  { quality: 50, destinationType: destinationType.FILE_URI, sourceType: source });
            }

            //获取照片成功
            function onPhotoURISuccess(imageURI) {
                //打印出照片路径
                console.log(imageURI);
                //显示照片
                var largeImage = document.getElementById('largeImage');
                largeImage.style.display = 'block';
                largeImage.src = imageURI;

                upload(imageURI);
            }

          //上传文件
          function upload(fileURL) {

            //上传成功
            var success = function (r) {
                console.log("上传成功! Code = " + r.responseCode);
            }

            //上传失败
            var fail = function (error) {
                alert("上传失败! Code = " + error.code);
            }

            var options = new FileUploadOptions();
            options.fileKey = "file1";
            options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
            //options.mimeType = "text/plain";

            //上传参数
            var params = {};
            params.value1 = "test";
            params.value2 = "param";
            options.params = params;

            var ft = new FileTransfer();
            //上传地址
            var SERVER = "http://www.hangge.com/upload.php"
            ft.upload(fileURL, encodeURI(SERVER), success, fail, options);
          };

        </script>
    </head>
    <body style="padding-top:50px">
        <button style="font-size:23px;" onclick="getPhoto(pictureSource.PHOTOLIBRARY);">
            从相册选择照片并上传
        </button> <br>
        <img style="display:none;" id="largeImage" src="" width="300px" />
    </body>
</html>

3,拍照并上传
下面代码样例,当点击按钮后会掉用摄像头拍照,并在页面上显示出来。同时拍摄照片会上传到服务器上。
             
<!DOCTYPE html>
<html>
    <head>
        <title>Capture Photo</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

            var destinationType;

            document.addEventListener("deviceready",onDeviceReady,false);

            //Cordova加载完成会触发
            function onDeviceReady() {
                destinationType=navigator.camera.DestinationType;
            }

            //拍照
            function capturePhoto() {
                //拍照并获取Base64编码的图像(quality : 存储图像的质量,范围是[0,100])
                navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
                                            destinationType: destinationType.FILE_URI }
                                            );
            }

            //拍照成功
            function onPhotoDataSuccess(imageURL) {
                var smallImage = document.getElementById('smallImage');
                smallImage.style.display = 'block';
                smallImage.src = imageURL;
                //开始上传
                upload(imageURL);
            }

            //拍照失败
            function onFail(message) {
                alert('拍照失败: ' + message);
            }

            //上传文件
            function upload(fileURL) {

              //上传成功
              var success = function (r) {
                  console.log("上传成功! Code = " + r.responseCode);
              }

              //上传失败
              var fail = function (error) {
                  alert("上传失败! Code = " + error.code);
              }

              var options = new FileUploadOptions();
              options.fileKey = "file1";
              options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
              options.mimeType = "image/jpeg";

              //上传参数
              var params = {};
              params.value1 = "test";
              params.value2 = "param";
              options.params = params;

              var ft = new FileTransfer();
              //上传地址
              var SERVER = "http://www.hangge.com/upload.php"
              ft.upload(fileURL, encodeURI(SERVER), success, fail, options);
            };
        </script>
    </head>
    <body style="padding-top:50px">
        <button style="font-size:23px;" onclick="capturePhoto();">拍摄照片并上传</button> <br>
        <img style="display:none;width:240px;height:320px;" id="smallImage" src="" />
    </body>
</html>

附:服务端代码(upload.php)

<?
$value1 = $_POST["value1"];
$value2 = $_POST["value2"];
  
move_uploaded_file($_FILES["file1"]["tmp_name"],
    $_SERVER["DOCUMENT_ROOT"]."/upload/" . $_FILES["file1"]["name"]);
 
echo "服务器收到如下数据:\r";
echo $value1."\r";
echo $value2."\r";
echo $_FILES["file1"]["name"]."\r";
?>
评论

全部评论(1)

回到顶部