从Android设备到PHP服务器的任何类型的Fileupload

时间:2016-02-11 17:56:07

标签: php android file-upload

我的代码只是将文件转换为byte array,然后再将其转换为Base64 Encoded format,以便我们可以将参数发布到URL。在服务器端,我们{{1}它返回并将其写入文件。使用volley库完成与服务器的连接。这个代码应该共享,因为我花了3天时间找到Android文件上传的解决方案。

  

此代码正常工作

的config.php

decodes

fileupload.php

<?php 
/***
* @Source: devshed
* @author E-Oreo
* http://forums.devshed.com/php-faqs-stickies-167/program-basic-secure-login-system-using-php-mysql-891201.html
*/
    // These variables define the connection information for your MySQL database 
    $username = "root"; 
    $password = ""; 
    $host = "localhost"; 
    $dbname = "clearsta_smt"; 

// UTF-8 is a character encoding scheme that allows you to conveniently store 
    // a wide varienty of special characters, like ¢ or €, in your database. 
    // By passing the following $options array to the database connection code we 
    // are telling the MySQL server that we want to communicate with it using UTF-8 
    // See Wikipedia for more information on UTF-8: 
    // http://en.wikipedia.org/wiki/UTF-8 
    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

    // A try/catch statement is a common method of error handling in object oriented code. 
    // First, PHP executes the code within the try block.  If at any time it encounters an 
    // error while executing that code, it stops immediately and jumps down to the 
    // catch block.  For more detailed information on exceptions and try/catch blocks: 
    // http://us2.php.net/manual/en/language.exceptions.php 
    try 
    { 
        // This statement opens a connection to your database using the PDO library 
        // PDO is designed to provide a flexible interface between PHP and many 
        // different types of database servers.  For more information on PDO: 
        // http://us2.php.net/manual/en/class.pdo.php 
        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
    } 
    catch(PDOException $ex) 
    { 
        // If an error occurs while opening a connection to your database, it will 
        // be trapped here.  The script will output an error and stop executing. 
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code 
        // (like your database username and password). 
        die("Failed to connect to the database: " . $ex->getMessage()); 
    } 

    // This statement configures PDO to throw an exception when it encounters 
    // an error.  This allows us to use try/catch blocks to trap database errors. 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    // This statement configures PDO to return database rows from your database using an associative 
    // array.  This means the array will have string indexes, where the string value 
    // represents the name of the column in your database. 
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 

    // This block of code is used to undo magic quotes.  Magic quotes are a terrible 
    // feature that was removed from PHP as of PHP 5.4.  However, older installations 
    // of PHP may still have magic quotes enabled and this code is necessary to 
    // prevent them from causing problems.  For more information on magic quotes: 
    // http://php.net/manual/en/security.magicquotes.php 
    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) 
    { 
        function undo_magic_quotes_gpc(&$array) 
        { 
            foreach($array as &$value) 
            { 
                if(is_array($value)) 
                { 
                    undo_magic_quotes_gpc($value); 
                } 
                else 
                { 
                    $value = stripslashes($value); 
                } 
            } 
        } 

        undo_magic_quotes_gpc($_POST); 
        undo_magic_quotes_gpc($_GET); 
        undo_magic_quotes_gpc($_COOKIE); 
    } 

    // This tells the web browser that your content is encoded using UTF-8 
    // and that it should submit content back to you using UTF-8 
    header('Content-Type: text/html; charset=utf-8'); 

    // This initializes a session.  Sessions are used to store information about 
    // a visitor from one web page visit to the next.  Unlike a cookie, the information is 
    // stored on the server-side and cannot be modified by the visitor.  However, 
    // note that in most cases sessions do still use cookies and require the visitor 
    // to have cookies enabled.  For more information about sessions: 
    // http://us.php.net/manual/en/book.session.php 
    session_start(); 

    // Note that it is a good practice to NOT end your PHP files with a closing PHP tag. 
    // This prevents trailing newlines on the file from being included in your output, 
    // which can cause problems with redirecting users.

?>

AddFile.java

<?php

require('config.php');
date_default_timezone_set('Asia/Kolkata');

if(!empty($_POST)){

    if(empty($_POST['inputUid']) || empty($_POST['inputFname']) ||empty($_POST['uploadedfile'])){
        $response["error"]=true;
        $response["success"] = 0;
        $response["message"] = "Error in connection";
        die(json_encode($response));
    }
    else{

        $uploadedfile = $_POST['uploadedfile'];

        $filename = $_POST['inputUid'].date("d-m-Y-h-i").$_POST['inputFname'];

        $query = "INSERT INTO tbl_cloud (cluid,clfile,cldate) VALUES (:puid,:pfile,:pdate)";

        $query_params = array(
            ':puid' => $_POST['inputUid'],
            ':pfile' => $filename,
            ':pdate' => date("d/m/Y h:i:sa"),
        );

        try {
            $stmt = $db->prepare($query);
            $result = $stmt->execute($query_params);
            $path = "uploads/$filename";
            file_put_contents($path,base64_decode($uploadedfile));           

        } catch (PDOException $ex) {
            $response['error']=true;
            $response['success'] = 0 ;
            $response['message'] = "Database Error1, Please try Again";
            die(json_encode($response));
        }

        $response['error']=false;
        $response['success']=1;
        $response['message']="The file has been uploaded";
        echo json_encode($response);

    }
}

?>

content_add_file.xml

package com.smt.smartmoneytracker;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.smt.smartmoneytracker.app.AppConfig;
import com.smt.smartmoneytracker.app.AppController;
import com.smt.smartmoneytracker.helper.SessionManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AddFile extends AppCompatActivity {

    Button b,b1;
    TextView messageText;
    SessionManager session;

    private static final int SELECT_FILE = 1;
    private String selectedImagePath;
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private String saq;
    private String asd;
    private String sdd;
    private String uid;
    private String sss;
    private String fff;
    private String nnn;

    private ProgressDialog loading = null;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_file);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        session = new SessionManager(getApplicationContext());
        b =  (Button) findViewById(R.id.btnfile);
        b1 = (Button) findViewById(R.id.button);
        messageText =(TextView) findViewById(R.id.messageText);

        //First button action
        b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setType("file/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select File"), SELECT_FILE);
            }}
        );
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //Getting userid, rawfile, filename
                uid = session.getUserid();
                sss = getBase64();
                nnn = getFname();

                String tag_string_req = "req_login";
                StringRequest strReq = new StringRequest(Request.Method.POST,
                        AppConfig.URL_FILEUP, new Response.Listener<String>() {
                    ProgressDialog loading = ProgressDialog.show(AddFile.this,"Uploading...","Please wait...",false,false);
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Upload Response: " + response.toString());

                        try {
                            loading.dismiss();
                            JSONObject jObj = new JSONObject(response);
                            boolean error = jObj.getBoolean("error");
                            String msg = jObj.getString("message");

                            if (!error) {
                                Toast.makeText(getApplicationContext(),msg, Toast.LENGTH_LONG).show();
                            } else {
                                // Get the error message
                                String errorMsg = jObj.getString("message");
                                Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        loading.dismiss();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Resposne Error: " + error.getMessage());
                        loading.dismiss();
                        Toast.makeText(getApplicationContext(),
                                "No Internet Connection/Network Problem", Toast.LENGTH_LONG).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        // Posting parameters to login url
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("inputUid",uid);
                        params.put("uploadedfile", sss);
                        params.put("inputFname", nnn);
                        return params;
                    }
                };
                AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_FILE) {
                Uri selectedImageUri = data.getData();

                //Getting image path
                selectedImagePath = getPath(selectedImageUri);

                Toast.makeText(AddFile.this,selectedImagePath,Toast.LENGTH_LONG).show();

                //Getting file name
                Cursor returnCursor = getContentResolver().query(selectedImageUri, null, null, null, null);
                  /*
                     * Get the column indexes of the data in the Cursor,
                     * move to the first row in the Cursor, get the data,
                     * and display it.
                  */
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                returnCursor.moveToFirst();
                String fname =  returnCursor.getString(nameIndex);
                messageText.setText(fname);
                setFname(fname);

                File file = new File(selectedImagePath);
                byte[] b = new byte[(int) file.length()];
                try {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    fileInputStream.read(b);
                    for (int i = 0; i < b.length; i++) {
                    }
                    String s = Base64.encodeToString(b, Base64.DEFAULT);
                    setBase64(s);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        }
    }
    public void setFname(String sdd){
        this.sdd =sdd;
    }
    public String getFname(){
        return sdd;
    }
    public String getBase64() {
        return saq;
    }
    public void setBase64(String saq) {
        this.saq = saq;
    }
    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
}

0 个答案:

没有答案