Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/193.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
任何类型的文件从Android设备上传到php服务器_Php_Android_File Upload - Fatal编程技术网

任何类型的文件从Android设备上传到php服务器

任何类型的文件从Android设备上传到php服务器,php,android,file-upload,Php,Android,File Upload,我的代码只是将文件转换为字节数组,然后再次将其转换为Base64编码格式,这样我们就可以将其作为参数发布到URL。在服务器端,我们将其解码并将其写入文件。使用volley库与服务器建立连接。此代码应该是共享,因为我花了3天时间才找到android文件上传的解决方案 此代码有效 config.php <?php /*** * @Source: devshed * @author E-Oreo * http://forums.devshed.com/php-faqs-stickies-167

我的代码只是将文件转换为
字节数组
,然后再次将其转换为
Base64编码格式
,这样我们就可以将其作为参数发布到
URL
。在服务器端,我们
将其解码
并将其写入文件。使用volley库与服务器建立连接。此代码应该是共享,因为我花了3天时间才找到android文件上传的解决方案

此代码有效

config.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.

?>
<?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);

    }
}

?>

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.

?>
<?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);

    }
}

?>

AddFile.java

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);
    }
}
package com.smt.smartmoneytracker;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.database.Cursor;
导入android.net.Uri;
导入android.os.Bundle;
导入android.provider.MediaStore;
导入android.provider.OpenableColumns;
导入android.support.v7.app.AppActivity;
导入android.support.v7.widget.Toolbar;
导入android.util.Base64;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.android.volley.Request;
导入com.android.volley.Response;
导入com.android.volley.VolleyError;
导入com.android.volley.toolbox.StringRequest;
导入com.smt.smartmoneytracker.app.AppConfig;
导入com.smt.smartmoneytracker.app.AppController;
导入com.smt.smartmoneytracker.helper.SessionManager;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.IOException;
导入java.util.HashMap;
导入java.util.Map;
公共类AddFile扩展了AppCompatActivity{
按钮b,b1;
文本查看消息文本;
会话管理器会话;
私有静态最终int选择_文件=1;
私有字符串selectedImagePath;
私有静态最终字符串标记=RegisterActivity.class.getSimpleName();
私有字符串saq;
私人字符串asd;
私人字符串sdd;
私有字符串uid;
私有字符串sss;
私有字符串fff;
私有字符串nnn;
private ProgressDialog加载=null;
@凌驾
创建时受保护的void(最终捆绑包savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u add\u文件);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
session=newsessionmanager(getApplicationContext());
b=(按钮)findViewById(R.id.btnfile);
b1=(按钮)findViewById(R.id.Button);
messageText=(TextView)findViewById(R.id.messageText);
//第一个按钮动作
b、 setOnClickListener(新视图。OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
意图=新意图();
intent.setType(“file/*”);
intent.setAction(intent.ACTION\u GET\u CONTENT);
startActivityForResult(Intent.createChooser(Intent,“选择文件”),选择文件);
}}
);
b1.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
//获取用户ID、原始文件、文件名
uid=session.getUserid();
sss=getBase64();
nnn=getFname();
String tag\u String\u req=“req\u login”;
StringRequest strReq=新的StringRequest(Request.Method.POST,
AppConfig.URL\u FILEUP,新的Response.Listener(){
ProgressDialog加载=ProgressDialog.show(AddFile.this,“上载…”,“请稍候…”,false,false);
@凌驾
公共void onResponse(字符串响应){
Log.d(标记“Upload Response:+Response.toString());
试一试{
loading.dispose();
JSONObject jObj=新的JSONObject(响应);
布尔错误=jObj.getBoolean(“错误”);
String msg=jObj.getString(“消息”);
如果(!错误){
Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG.show();
}否则{
//获取错误消息
字符串errorMsg=jObj.getString(“消息”);
Toast.makeText(getApplicationContext(),errorMsg,Toast.LENGTH_LONG.show();
}
}捕获(JSONException e){
e、 printStackTrace();
}
loading.dispose();
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(标记“Resposne Error:+Error.getMessage());
loading.dispose();
Toast.makeText(getApplicationContext(),
“没有互联网连接/网络问题”,Toast.LENGTH_LONG.show();
}
}) {
@凌驾
受保护的映射getParams(){
//将参数发布到登录url
Map params=新的HashMap();
参数put(“inputUid”,uid);
参数put(“uploadedfile”,sss);
参数put(“inputFname”,nnn);
返回参数;
}
};
AppController.getInstance().addToRequestQueue(streq,标记字符串请求);
}
});
getSupportActionBar().setDisplayHomeAs