如何使用Android Phonegap将文件从SD卡中的任何文件夹上传到服务器

时间:2013-07-25 14:18:46

标签: android file-upload cordova

我收到错误消息“Object object”。我在SD卡中有一个文件夹。我想将其上传到服务器。我的服务器上有一个upload.php。

    function local() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
        window.resolveLocalFileSystemURI("file:///TestFolder/1.jpg", uploadOffline, fail);
    }
    function uploadOffline(fileEntry){
    checkConnection();

    var options = new FileUploadOptions();
    options.fileKey="file";
    options.mimeType="image/jpeg";

    var params = new Object();
    params.value1 = "test1";
    params.value2 = "param1";

    options.params = params;
    options.chunkedMode = false;
    var uri = fileEntry.toURI();
    var ft = new FileTransfer();
    ft.upload(uri, "http://www.myurl.com/upload.php", win, fail, options);
    }

2 个答案:

答案 0 :(得分:0)

我使用此方法上传日志文件。您必须更改文件和服务器地址的路径。 如果你不知道ip地址10.0.2.2是你的localhost的android别名。我从其他网站获得此方法。我刚刚更改了文件路径和服务器地址。

private void uploadMedia() throws IOException {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile ="/data/data/com.jos.finalsolution/files/LocationData";
    String urlServer = "http://10.0.2.2/phpvt/receiver.php";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;

    try
    {
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
    outputStream.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    int serverResponseCode = connection.getResponseCode();
    String serverResponseMessage = connection.getResponseMessage();
    fileInputStream.close();
    outputStream.flush();
    outputStream.close();

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    //Exception handling
    }

}

答案 1 :(得分:0)

不知道您是否找到了问题的解决方案,但也许这些代码可以帮助您。

function files() {
    alert("Let's Start")    
     window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, 
        function gotFS(fileSystem) {
            fileSys = fileSystem;
        }
        , fsFail);

    fileSys.root.getDirectory("myFolder/", {create: true, exclusive: false},  
        function(parent) {
            folder=parent;
        }
        , dirFail);

        //Creating a reader
        var directoryReader = folder.createReader();
        // Get a list of all the entries in the directory
        directoryReader.readEntries(ReaderSucces,readerFail);   

    function ReaderSucces(entries){
        alert("I'm reading")
        var i,len;
        len = entries.length;
        for (i=0; i<len; i++) {
            if (entries[i].isDirectory) {
                 var directoryReaderIn = entries[i].createReader();
                directoryReaderIn.readEntries(ReaderSucces,readingFail); 
            }
             if(entries[i].isFile==true)
            {
            entries[i].file(uploadFile, readingFail);
            }
        }
    }

    var fsFail = function(error) {
            alert("failed with error code: " + error.code);
    };                  
    var dirFail = function(error) {
        alert("Directory error code: " + error.code);
    };
    var readerFail = function(error) {
        alert("Reading Directory error code: " + error.code);
    };          
    var readingFail = function (error){
        console.log("Reading Files error code: "+error.code);
    };
}

function uploadFile(file) {
    console.log("Let's upload!!!" + file)
    var target="http://YOUR_IP/upload.php"; //the url to upload on server
    var ft = new FileTransfer();
    var path = file.fullPath; //"file://"+ 
    var name = file.name;

    var ft = new FileTransfer();

    ft.upload(path, encodeURI(target), win, fail, { fileName: name, fileKey: "file", mimeType:"text/plain" });
           // var ft = new FileTransfer();
          //ft.upload(file.fullPath, target, win, fail, options);
}

服务器中的PHP(upload.php)

    <?php
if ($_FILES["file"]["error"] > 0) {
  echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
  echo "Upload: " . $_FILES["file"]["name"] . "\n " ; 
  echo "Type: " . $_FILES["file"]["type"] . "\n ";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb\n ";
  echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<\n ";
  if (file_exists("uploads/" . $_FILES["file"]["name"])) {
    echo $_FILES["file"]["name"] . " already exists. ";
  } else {
    move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]); //Save location
    echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
  }
}
?>

它将保存位于文件夹中的所有文件(甚至是目录中的文件)。希望它有效。