简体   繁体   English

使用 PHP 脚本从 android 应用程序上传 SQLite 数据库文件

[英]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.我正在尝试将 SQLite 数据库文件“.db”从我的 android 应用程序上传到 PHP 服务器。 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.到目前为止,我一直关注这篇文章https://stackoverflow.com/a/25398566 ,我得到的只是来自我的服务器的“200”成功响应,并且文件没有发布。 There are no error messages on my app or server logs.我的应用程序或服务器日志中没有错误消息。 Here's my upload function:这是我上传的 function:

Android Code: Android 代码:

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 代码:

<?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; android function 没问题; 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. PHP 脚本也上传到我的根目录而不是我的首选文件夹。 I had to change this line:我不得不改变这一行:

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

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

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