简体   繁体   中英

Uploading an SQLite database file from android app using a PHP script

I am trying to upload an SQLite database file ".db" from my android app to a PHP server. I have so far followed this post https://stackoverflow.com/a/25398566 and all I am getting is a "200" success response from my server and the file is not posting. There are no error messages on my app or server logs. Here's my upload function:

Android Code:

private class UploadFileAsync extends AsyncTask<String, Void, String> {
    private Context mContext;
    private ContentResolver mContentResolver;

    public UploadFileAsync(Context context, ContentResolver resolver) {
        mContext = context;
        mContentResolver = resolver;
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            String sourceFileUri = params[0]; //*Uri.fromFile(context.getDatabasePath(myDBHelper.getDatabaseName())).toString();*
            String fileName = params[1];


            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;

            File sourceFile = mContext.getDatabasePath(myDBHelper.getDatabaseName());


            if (sourceFile.isFile()) {

                try {
                    String upLoadServerUri = "https://website.com/script.php?";

                    // open a URL connection to the Servlet
                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);
                    URL url = new URL(upLoadServerUri);

                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true); // Allow Inputs
                    conn.setDoOutput(true); // Allow Outputs
                    conn.setUseCaches(false); // Don't use a Cached Copy
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("ENCTYPE",
                            "multipart/form-data");
                    conn.setRequestProperty("Content-Type",
                            "multipart/form-data;boundary=" + boundary);
                    conn.setRequestProperty("sqlite", sourceFileUri);

                    dos = new DataOutputStream(conn.getOutputStream());

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"sqlite\";filename=\""
                            + sourceFileUri + "\"" + lineEnd);

                    dos.writeBytes(lineEnd);

                    // create a buffer of maximum size
                    bytesAvailable = fileInputStream.available();

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

                    // read file and write it into form...
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                    while (bytesRead > 0) {

                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math
                                .min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0,
                                bufferSize);

                    }

                    // send multipart form data necesssary after file
                    // data...
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens
                            + lineEnd);

                    // Responses from the server (code and message)
                    int serverResponseCode = conn.getResponseCode();
                    String serverResponseMessage = conn
                            .getResponseMessage();

                    if (serverResponseCode == 200) {


                        Log.d("uploadFile", "Success > HTTP Response is : "
                                + serverResponseMessage + ": " + serverResponseCode);

                        // recursiveDelete(mDirectory1);                       

                    }

                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                } catch (Exception e) {

                    // dialog.dismiss();
                    e.printStackTrace();

                }
                // dialog.dismiss();

            } // End else block


        } catch (Exception ex) {
            // dialog.dismiss();

            ex.printStackTrace();
        }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

PHP code:

<?php

if (is_uploaded_file($_FILES['sqlite']['tmp_name'])) {
    $uploads_dir = './folder';
    $tmp_name = $_FILES['sqlite']['tmp_name'];
    $db_name = $_FILES['sqlite']['name'];

    if(move_uploaded_file($tmp_name, $uploads_dir.$db_name)){
        echo 'success';
    }else{
        echo 'fail';
    }

}else{
    echo "File not uploaded successfully.";
}

   ?>

What am I doing wrong?

The android function is fine; the issue is I had to copy the database to external storage first and upload the copy instead. The PHP script was also uploading to my root directory instead of my preferred folder. I had to change this line:

$uploads_dir = $_SERVER['DOCUMENT_ROOT'] . '/folder_name/';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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