简体   繁体   English

使用Phonegap上传图像:InvalidCastException

[英]Upload an image with Phonegap: InvalidCastException

I am trying to upload a file to my server with Phonegap. 我正在尝试使用Phonegap将文件上传到我的服务器。 I am currently stuck when an error that says: 当出现以下错误消息时,我目前陷入困境:

InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]

The HTML + Javascript HTML + Javascript

<!DOCTYPE html>
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="format-detection" content="telephone=no" />
    <title>File Transfer Example</title>

</head>
<body>
    <button id="uploadPhotoButton">Upload a Photo</button>

    <script type="text/javascript" src="cordova-2.2.0.js"></script>
    <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="js/jquery.mobile-1.2.0.min.js"></script>
    <script type="text/javascript" src="js/camera.js"></script>
    <script type="text/javascript">

    $(document).one("pause", function () {
        console.log('Paused.');
    });

    $(document).one("resume", function () {
        console.log('Resumed.');
    });

    $(document).one("deviceready", function () {
        console.log('Device is ready.');
    });

    $(document).one("backbutton", function () {
        console.log('Back button pressed.');
    });

    $(document).ready(function () {
        console.log('DOM is ready.');

        $(document).on("click", "#uploadPhotoButton", function (e) {
            console.log('clicked button');
            getImage();
        });


        function getImage() {
            // Retrieve image file location from specified source
                navigator.camera.getPicture(uploadPhoto, function (message) {
                    alert('get picture failed');
                }, {
                    quality: 50,
                    destinationType: navigator.camera.DestinationType.FILE_URI,
                    sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
                }
            );

        }

        function uploadPhoto(imageURI) {
            var options = new FileUploadOptions();
            options.fileKey = "file";
            options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
            options.mimeType = "image/jpeg";

            var params = new Object();
            params.value1 = "test";
            params.value2 = "param";

            options.params = params;
            options.chunkedMode = false;

            var ft = new FileTransfer();
            ft.upload(imageURI, "http://my.server.co.nz/pages/fileupload", win, fail, options);
        }

        function win(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
            alert(r.response);
        }

        function fail(error) {
            alert("An error has occurred: Code = " = error.code);
        }
    });

    </script>
    </body>
</html>

The complete error log. 完整的错误日志。

GapBrowser_Navigated :: /app/www/index.html#/app/www/uploadtest.html
Log:"clicked button"
The thread '<No Name>' (0xf55026a) has exited with code 0 (0x0).
The thread '<No Name>' (0xe3f0326) has exited with code 0 (0x0).
INFO: AppDeactivated
INFO: AppActivated
Log:"Paused."
The thread '<No Name>' (0xf1a02e6) has exited with code 0 (0x0).
Log:"Resumed."
The thread '<No Name>' (0xf2a01d2) has exited with code 0 (0x0).
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.NullReferenceException' occurred in Lion.MyApp.dll
The thread '<No Name>' (0xfdc025e) has exited with code 0 (0x0).
Log:"Error in error callback: FileTransfer1325332352 = ReferenceError: Invalid left-hand side in assignment"
The thread '<No Name>' (0xfa60286) has exited with code 0 (0x0).

Does anyone have an idea on how to make this work? 是否有人对如何进行这项工作有任何想法?

Thanks! 谢谢!

W w ^

I'm thinking that you are malforming your options value. 我认为您的期权价值不正确。 Do you need to pass JSON or an actual object? 您是否需要传递JSON或实际对象?

Right now you are passing an array with text in it. 现在,您正在传递一个包含文本的数组。

options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]

The error seems to involve deserialization issues. 该错误似乎涉及反序列化问题。

Put your getImage, uploadImage, win, fail outside of $(document).ready 's inline function call. 将您的getImage,uploadImage,win,失败放在$(document).ready的内联函数调用之外。

Reference to win and fail are actually closure, and phone gap gets it as null when it is trying to access those methods directly. 对成功和失败的引用实际上是封闭的,当尝试直接访问这些方法时,电话间隙将其获取为null。 Phonegap is probably expecting a global function instead of hidden function inside a function. Phonegap可能期望使用全局函数而不是函数内部的隐藏函数。

PhoneGap's executes its code out side javascript context, what may work in true javascript fashion may not work correctly with phonegap. PhoneGap会在javascript上下文之外执行其代码,以true javascript方式工作的内容可能无法在phonegap上正常工作。

I had a problem similar to yours. 我有一个与您相似的问题。 I solved this, changing mimeType parameter to 'text/plain'. 我解决了这个问题,将mimeType参数更改为'text / plain'。

Do you use params to send? 您是否使用params发送? If it's false I think you need send empty params. 如果为假,我认为您需要发送空参数。

I had this problem before, try to prepare the image in the html first, and dont take it directly from the navigator, it may not saving the taken photo in it cash ;) 我之前遇到过这个问题,尝试先在html中准备图像,并且不要直接从导航器中获取图像,它可能不会将所拍摄的照片保存在现金中;)

In my solution I suppose to have an image tage with id ='camera_image' 在我的解决方案中,我想有一个id ='camera_image'的图像年龄

img id='camera_image'... img id ='camera_image'...

Then i set all the variables of the image in it and I upload it (as you will see in the following code). 然后,在其中设置图像的所有变量,然后上传(如下面的代码所示)。

here's the 2 functions i used: 这是我使用的2个功能:

function takephoto(){     

      navigator.camera.getPicture(      
        function(uri){
             $('#camera_image').show();
             var img = document.getElementById('camera_image');
             img.style.visibility = "visible"; 
             img.style.display = "block";
             img.src = uri;
             uploadPhoto(img);                    
             alert("Success");
         },
         function(e) {
             console.log("Error getting picture: " + e);
         },
         {
             quality: 50, 
             destinationType: navigator.camera.DestinationType.FILE_URI
         });

        // Get URI of picture to upload 
        var img = document.getElementById('camera_image');
        var imageURI = img.src;
        if (!imageURI || (img.style.display == "none")) {
                alert("Take picture or select picture from library first.");
                return;
        }
}

for choosing an existing photo: 用于选择现有照片:

 function choosephoto(){
    navigator.camera.getPicture(
        function(uri) {
            $('#camera_image').show();
            var img = document.getElementById('camera_image');
            img.style.visibility = "visible"; 
            img.style.display = "block";
            img.src = uri;
            uploadPhoto(img);
        },
        function(e) {
            console.log("Error getting picture: " + e);
        },
        {
             quality: 50, 
             destinationType: navigator.camera.DestinationType.FILE_URI, 
             sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM
        });             

        // Get URI of picture to upload
        var img = document.getElementById('camera_image');
        var imageURI = img.src;
        if (!imageURI || (img.style.display == "none")) {
            alert("please select a pic first");
            return;
        }

  }

in the upload function: function uploadPhoto(img) { imageURI = img.src ... 在上传功能中:function uploadPhoto(img){imageURI = img.src ...

ps: sorry for the formatting of my code, it doesn't fix well. ps:很抱歉,我的代码格式不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM