ios 从相机/照片库上传 Ionic 应用程序图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30534820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:07:40  来源:igfitidea点击:

Ionic app image upload from camera / photo library

ioscameraionic-frameworkfile-transferngcordova

提问by user1242574

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.

我正在开发一个离子聊天应用程序,用户可以在其中上传照片作为他们消息的一部分。我正在寻找一种将图像上传到我的虚拟主机服务器的方法,以便我稍后可以通过 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
  • org.apache.cordova.file-transfer
  • 科尔多瓦插件相机

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

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

  • 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: ""
  • 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:


这是我的 upload.php 文件:

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

回答by user1242574

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:

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

<?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";
  }
}
?>

回答by Jess Patton

the app I am building for a company had the same issue, what we did is we just posted the image to our server as a base64 string. Then you can simple pull the string from the database and display it in a div. We used the NgCordova camera and then just pass in the data from the takePhoto function.

我为一家公司构建的应用程序也有同样的问题,我们所做的只是将图像作为 base64 字符串发布到我们的服务器上。然后,您可以简单地从数据库中提取字符串并将其显示在 div 中。我们使用了 NgCordova 相机,然后从 takePhoto 函数传入数据。

$scope.takePhoto = function () {
            $ionicScrollDelegate.scrollTop();
            console.log('fired camera');
            $scope.uploadList = false;
            $ionicPlatform.ready(function() {
                var options = {
                    quality: 100,
                    destinationType: Camera.DestinationType.DATA_URL,
                    sourceType: Camera.PictureSourceType.CAMERA,
                    allowEdit: false,
                    encodingType: Camera.EncodingType.PNG,
                    targetWidth: 800,
                    targetHeight: 1100,
                    popoverOptions: CameraPopoverOptions,
                    saveToPhotoAlbum: false
                };
                $cordovaCamera.getPicture(options).then(function (imageData) {
                    $ionicLoading.show({
                        template: 'Processing Image',
                        duration: 2000
                    });
                    $scope.image = "data:image/png;base64," + imageData;
                    if (ionic.Platform.isAndroid() === true) {
                        $scope.Data.Image = LZString.compressToUTF16($scope.image);
                        $scope.Data.isCompressed = 1;
                    } else {
                        $scope.Data.Image = $scope.image;
                        $scope.Data.isCompressed = 0;
                    }
                    if ($scope.tutorial) {
                        $scope.showAlert("Instructions: Step 3", '<div class="center">Now that you have taken a photo of the POD form, you must upload it to the server. Press the upload doc button in the bottom right of the screen.</div>');
                    }
                    $scope.on('')
                }, function (err) {
                    console.log(err);
                });
            }, false);
        };

 $scope.UploadDoc = function () {
            var req = {
                method: 'POST',
                url: ffService.baseUrlAuth + 'cc/upload',
                headers: {
                    'x-access-token': ffService.token
                },
                data: $scope.Data
            };
            if ($scope.Data.Image === null || $scope.Data.Value === '') {
                $scope.showAlert("Uh Oh!", '<div class="center">Please take a photo of your document before attempting an upload.</div>');
            } else {
                $http(req).success(function (data, status, headers, config) {
                    localStorage.setItem('tutorial', false);
                    $scope.tutorial = false;
                    $scope.getUploads($scope.PODOrder.OrderNo);
                    $scope.showAlert("Success!", '<div class="center">Your Document has been successfully uploaded!</div>');
                    $scope.uploadList = true;
                }).error(function (data, status, headers, config) {
                    $rootScope.$broadcast('loading:hide');
                    $scope.showAlert("Something went wrong!", '<div class="center">Please make sure you have an internet connection and try again.</div>');
                }).then(function(data, status, headers, config){
                    $scope.Data.Image = null;
                });
            }
        };