从相机/照片库中上传Ionic应用图片 [英] Ionic app image upload from camera / photo library

查看:293
本文介绍了从相机/照片库中上传Ionic应用图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发离子聊天应用程序,用户可以在其中上传照片作为其消息的一部分。我正在寻找一种方法将图像上传到我的webhost服务器,所以我以后可以通过URL来检索它。



问题是,我不能



b
  • org.apache.cordova.file-transfer

  • cordova-plugin-camera



  • 当我在xcode模拟器中运行应用程序并从设备照片库中选择一张图片时,控制台会给我以下信息:




    • code>文件传输用响应代码200完成

    • void SendDelegateMessage(NSInvocation *):delegate(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame :)等待10秒后无法返回。主运行循环模式:kCFRunLoopDefaultMode>

    • SUCCESS:



    这是我目前使用的代码:

      app.controller('HomeController',function($ rootScope,$ scope,$ cordovaCamera,$ ionicActionSheet,$ cordovaFileTransfer){... 

    //打开PhotoLibrary
    $ scope.openPhotoLibrary = function(){
    var options = {
    quality:100,
    destinationType:Camera.DestinationType.FILE_URI,
    sourceType:Camera.PictureSourceType.PHOTOLIBRARY,
    allowEdit: true,
    encodingType:Camera.EncodingType.JPEG,
    popoverOptions:CameraPopoverOptions,
    saveToPhotoAlbum:false
    };

    $ cordovaCamera.getPicture .then(function(imageData){

    //console.log(imageData);
    //console.log(options);

    var url = http://mydomein.com/upload.php;
    //目标路径可以是local或url
    var targetPath = imageData;
    var filename = targetPath.split(/)。pop();
    var options = {
    fileKey:file,
    fileName:filename,
    chunkedMode:false,
    mimeType:image / jpg
    } ;
    $ cordovaFileTransfer.upload(url,targetPath,options).then(function(result){
    console.log(SUCCESS:+ JSON.stringify(result.response));
    alert(success);
    alert(JSON.stringify(result.response));
    },function(err){
    console.log(ERROR:+ JSON.stringify (err));
    alert(JSON.stringify(err));
    },function(progress){
    //常量进度更新
    $ timeout(function
    $ scope.downloadProgress =(progress.loaded / progress.total)* 100;
    })
    });

    },function(err){
    // error
    console.log(err);
    });
    }



    这是我的upload.php文件: / p>

     <?php 
    // move_uploaded_file($ _ FILES [file] [tmp_name],$ cwd 。'/ files / images /');
    move_uploaded_file($ _ FILES [file] [tmp_name],/ files / images);
    ?>


    解决方案

    它工作。



    这是我想出的代码:

      // open PhotoLibrary 
    $ scope.openPhotoLibrary = function(){
    var options = {
    quality:50,
    destinationType:Camera.DestinationType.FILE_URI,
    sourceType:Camera.PictureSourceType.PHOTOLIBRARY,
    allowEdit:true,
    encodingType:Camera.EncodingType.JPEG,
    popoverOptions:CameraPopoverOptions,
    saveToPhotoAlbum:false
    };

    $ cordovaCamera.getPicture(options).then(function(imageData){

    //console.log(imageData);
    //console.log options);
    var image = document.getElementById('tempImage');
    image.src = imageData;

    var server =http://yourdomain.com/upload .php,
    filePath = imageData;

    var date = new Date();

    var options = {
    fileKey:file
    fileName:imageData.substr(imageData.lastIndexOf('/')+ 1),
    chunkedMode:false,
    mimeType:image / jpg
    };

    $ cordovaFileTransfer.upload(server,filePath,options).then(function(result){
    console.log(SUCCESS:+ JSON.stringify(result.response));
    console.log('Result_'+ result.response [0] +'_ending');
    alert(success);
    alert(JSON.stringify(result.response));

    },function(err){
    console.log(ERROR:+ JSON.stringify(err));
    //alert(JSON.stringify(err));
    },函数(进度){
    //持续进度更新
    });


    },function(err){
    // error
    console.log(err);
    });
    }

    域服务器上的upload.php中的代码:

     <?php 

    //如果要查找文件夹的根路径使用代码行以下:
    // echo $ _SERVER ['DOCUMENT_ROOT']


    if($ _FILES [file] [error]> 0){
    echo错误代码:。 $ _FILES [file] [错误]。 < br />;
    }
    else
    {
    echo已上传文件:。 $ _FILES [file] [name]。 < br />;
    echoType:。 $ _FILES [file] [type]。 < br />;
    echoSize:。 ($ _FILES [file] [size] / 1024)。 kilobytes< br />;

    if(file_exists(/ files /\".$_ FILES [file] [name]))
    {
    echo $ _FILES [file] [ 名称] 。 已经存在,没有笑话 - 这个错误几乎是< i>< b>不可能< / b>< / i>得到,再试一次,我打赌100万美元不会再发生。 ;
    }
    else
    {
    move_uploaded_file($ _ FILES [file] [tmp_name],/ var / www / vhosts / yourdomain.com / subdomains / domainname / httpdocs / foldername / images /\".$_ FILES [file] [name]);
    echoDone;
    }
    }
    ?>


    I'm working on a ionic chat app where the user can upload a photo as part of their message. I'm looking for a way to upload the image to my webhost server so I can retrieve it later via a URL.

    The problem is that I'm not able to get it to upload to my web server.

    I'm using these two plugins:

    • org.apache.cordova.file-transfer
    • cordova-plugin-camera

    When I run the app in xcode simulator and select a picture from the device photolibrary, the console gives me the following messages:

    • File Transfer Finished with response code 200
    • void SendDelegateMessage(NSInvocation *): delegate (webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode>
    • SUCCESS: ""

    This is the code I currently use:

    app.controller('HomeController', function($rootScope, $scope, $cordovaCamera, $ionicActionSheet, $cordovaFileTransfer){ ...
    
    // open PhotoLibrary
        $scope.openPhotoLibrary = function() {
            var options = {
                quality: 100,
                destinationType: Camera.DestinationType.FILE_URI,
                sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
                allowEdit: true,
                encodingType: Camera.EncodingType.JPEG,
                popoverOptions: CameraPopoverOptions,
                saveToPhotoAlbum: false
            };
    
            $cordovaCamera.getPicture(options).then(function(imageData) {
    
                //console.log(imageData);
                //console.log(options);
    
                var url = "http://mydomein.com/upload.php";
                //target path may be local or url
                var targetPath = imageData;
                var filename = targetPath.split("/").pop();
                var options = {
                    fileKey: "file",
                    fileName: filename,
                    chunkedMode: false,
                    mimeType: "image/jpg"
                };
                $cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
                    console.log("SUCCESS: " + JSON.stringify(result.response));
                    alert("success");
                    alert(JSON.stringify(result.response));
                }, function(err) {
                    console.log("ERROR: " + JSON.stringify(err));
                    alert(JSON.stringify(err));
                }, function (progress) {
                    // constant progress updates
                    $timeout(function () {
                        $scope.downloadProgress = (progress.loaded / progress.total) * 100;
                    })
                });
    
            }, function(err) {
                // error
                console.log(err);
            });
        }
    


    This is my upload.php file:

    <?php
    // move_uploaded_file($_FILES["file"]["tmp_name"], $cwd . '/files/images/');
    move_uploaded_file($_FILES["file"]["tmp_name"], "/files/images");
    ?>
    

    解决方案

    After some digging around and lot's of trying I finally got it working.

    This is the code I came up with:

    // open PhotoLibrary
        $scope.openPhotoLibrary = function() {
            var options = {
                quality: 50,
                destinationType: Camera.DestinationType.FILE_URI,
                sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
                allowEdit: true,
                encodingType: Camera.EncodingType.JPEG,
                popoverOptions: CameraPopoverOptions,
                saveToPhotoAlbum: false
            };
    
            $cordovaCamera.getPicture(options).then(function(imageData) {
    
                //console.log(imageData);
                //console.log(options);   
                var image = document.getElementById('tempImage');
                image.src = imageData;  
    
                var server = "http://yourdomain.com/upload.php",
                    filePath = imageData;
    
                var date = new Date();
    
                var options = {
                    fileKey: "file",
                    fileName: imageData.substr(imageData.lastIndexOf('/') + 1),
                    chunkedMode: false,
                    mimeType: "image/jpg"
                };
    
                $cordovaFileTransfer.upload(server, filePath, options).then(function(result) {
                    console.log("SUCCESS: " + JSON.stringify(result.response));
                    console.log('Result_' + result.response[0] + '_ending');
                    alert("success");
                    alert(JSON.stringify(result.response));
    
                }, function(err) {
                    console.log("ERROR: " + JSON.stringify(err));
                    //alert(JSON.stringify(err));
                }, function (progress) {
                    // constant progress updates
                });
    
    
            }, function(err) {
                // error
                console.log(err);
            });
        }
    

    And the code in upload.php on the domain server:

    <?php
    
    // if you want to find the root path of a folder use the line of code below:
    //echo $_SERVER['DOCUMENT_ROOT']
    
    
    if ($_FILES["file"]["error"] > 0){
    echo "Error Code: " . $_FILES["file"]["error"] . "<br />";
    }
    else
    {
    echo "Uploaded file: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kilobytes<br />";
    
    if (file_exists("/files/".$_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. No joke-- this error is almost <i><b>impossible</b></i> to get. Try again, I bet 1 million dollars it won't ever happen again.";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/vhosts/yourdomain.com/subdomains/domainname/httpdocs/foldername/images/".$_FILES["file"]["name"]);
      echo "Done";
      }
    }
    ?>
    

    这篇关于从相机/照片库中上传Ionic应用图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆