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

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

问题描述

我正在开发一款 ionic 聊天应用,用户可以在其中上传照片作为消息的一部分.我正在寻找一种方法将图像上传到我的虚拟主机服务器,以便我以后可以通过 URL 检索它.

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

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

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

  • 文件传输完成,响应代码为 200
  • void SendDelegateMessage(NSInvocation *):委托 (webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:) 在等待 10 秒后未能返回.主运行循环模式:kCFRunLoopDefaultMode>
  • 成功:""

这是我目前使用的代码:

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);
        });
    }


这是我的upload.php文件:


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.

这是我想出的代码:

// 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);
        });
    }

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

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天全站免登陆