PhoneGap Ajax上载文件

PhoneGap Ajax Upload File

本文关键字:文件 上载 Ajax PhoneGap      更新时间:2023-09-26

我正在尝试运行这个PhoneGap示例,以便将图像从设备上传到服务器。

    // Wait for PhoneGap to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);
    // PhoneGap is ready
    //
    function onDeviceReady() {
        // 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;
        var ft = new FileTransfer();
        ft.upload(imageURI, "http://some.server.com/upload.php", win, fail, options);
    }
    function win(r) {
        alert("Code = " + r.responseCode);
        alert("Response = " + r.response);
        console.log("Sent = " + r.bytesSent);
    }
    function fail(error) {
        alert("An error has occurred: Code = " + error.code);
        alert("upload error source " + error.source);
        alert("upload error target " + error.target);
    }

在我的例子中,与上面提到的例子不同,我没有使用将数据发布到数据库中的php文件,而是使用安全的url直接通过HTML发布。在桌面版本上看起来像这样的东西:

<form action="https://mySecureUrl.com/?filename=myImage" method="post" enctype="multipart/form-data">
<input type="file" name="myfile"><br>
<input type="submit" value="Upload File to Server">
</form>

现在我尝试使用PhoneGap FileTransfer()应用相同的方法,得到错误代码3。

var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("https://mySecureUrl.com/?filename=myImage.jpg"), win, fail, options);
  • 有可能在PhoneGap上以这种方式发布文件吗?如何
  • 如果没有,php解决方案是什么

options下的fileKey是服务器要查找的名称。在HTML中,名称设置为"myfile",在javascript中,名称为"file"。

<input type="file" name="myfile">
options.fileKey="file";

options.fileKey和属性名称是一样的,所以请确保您的PHP在$_FILES数组中查找"file"