Cordova相机图像无法使用文件传输上传

时间:2018-03-09 11:02:15

标签: angularjs cordova file-transfer

我目前正在做的事情是你可以拍照或从图库中选择一张并将其上传到服务器。我在使用cordova FileTransfer发送和上传图片时遇到了问题。它要么根本不发送,要么$_FILES["file"]是空的。

我有单独的按钮来调出相机和图库:

<button id="takePicture" name="takePicture" ng-click="openCamera();">Take Photo</button>
<button id="getPicture" name="getPicture" ng-click="openGallery();">Choose From Gallery</button>

解决方案:

$scope.openCamera = function()
{
    navigator.camera.getPicture(onSuccess, onError, 
    {   quality         : 100, 
        destinationType : Camera.DestinationType.FILE_URI
    });  

    function onSuccess(imageURI) 
    { 
        var options = new FileUploadOptions();

        options.fileKey     = "file";
        options.fileName    = imageURI.substr(imageURI.lastIndexOf("/")+1);
        options.mimeType    = "image/jpeg";
        options.httpMethod  = "POST";
        options.chunkedMode = false;
        options.params      = { filePath : imageURI.split("?")[0] };

        var fileTransfer = new FileTransfer;

        fileTransfer.upload(imageURI, encodeURI("upload.php"), uploadComplete, uploadError, options);

        function uploadComplete(result) 
        {
            console.log("Code = " + result.responseCode);
            console.log("Response = " + result.response);
            console.log("Sent = " + result.bytesSent);
        }

        function uploadError(error) 
        {
            alert("An error has occurred: Code = " + error.code);
            console.log("upload error source " + error.source);
            console.log("upload error target " + error.target);
        }
    }  

    function onError(message) 
    { 
        alert("fail");

        alert('Failed because: ' + message); 
    } 
}

然后将在upload.php文件上接收发送的数据。您应该可以通过检查文件var_dump($_FILES);

来检查数据是否已发送

Sletheren所述,也可以使用$cordovaFileTransfer.upload();

完成

1 个答案:

答案 0 :(得分:0)

这就是我的工作方式:

  • 第一件事:destinationType应为Camera.DestinationType.FILE_URI
  • 第二步:将文件名设置为:filename = imageURI.split('?')[0];
  • 第三:fileTransfer接受这些参数(它适用于我): $cordovaFileTransfer.upload(url, filename, options)