简体   繁体   English

将doc,pdf,xls等文件从android应用程序上传到php服务器

[英]Upload doc, pdf,xls etc, from android application to php server

I get stuck at that place and unable to send doc file to php server. 我被困在那个地方,无法将文档文件发送到php服务器。 I am using this code. 我正在使用此代码。

Here is PHP code. 这是PHP代码。

if($_SERVER['REQUEST_METHOD']=='POST'){

    $image = $_POST['image'];
            $name = $_POST['name'];

    require_once('dbConnect.php');

    $sql ="SELECT id FROM volleyupload ORDER BY id ASC";

    $res = mysqli_query($con,$sql);

    $id = 0;

    while($row = mysqli_fetch_array($res)){
            $id = $row['id'];
    }

    $path = "uploads/$id.doc";

    $actualpath = "http://10.0.2.2/VolleyUpload/$path";

    $sql = "INSERT INTO volleyupload (photo,name) VALUES ('$actualpath','$name')";

    if(mysqli_query($con,$sql)){
        file_put_contents($path,base64_decode($image));
        echo "Successfully Uploaded";
    }

    mysqli_close($con);
}else{
    echo "Error";
}

Here is Java code 这是Java代码

private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("file/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),
            PICK_IMAGE_REQUEST);
}

I called asynTask on upload button. 我在上传按钮上调用了asynTask。

if (v == buttonUpload) {
        // uploadImage();
        new PostDataAsyncTask().execute();
    }

A function calls in doInBackground is 在doInBackground中调用的函数是

private void postFile() {
    try {

        // the file to be posted
         String textFile = Environment.getExternalStorageDirectory()
         + "/Woodenstreet Doc.doc";
         Log.v(TAG, "textFile: " + textFile);

        // the URL where the file will be posted
        String postReceiverUrl = "http://10.0.2.2/VolleyUpload/upload.php";
        Log.v(TAG, "postURL: " + postReceiverUrl);

        // new HttpClient
        HttpClient httpClient = new DefaultHttpClient();

        // post header
        HttpPost httpPost = new HttpPost(postReceiverUrl);

        File file = new File(filePath.toString());
        FileBody fileBody = new FileBody(file);

        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("file", fileBody);
        httpPost.setEntity(reqEntity);

        // execute HTTP post request
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {

            String responseStr = EntityUtils.toString(resEntity).trim();
            Log.v(TAG, "Response: " + responseStr);

            // you can add an if statement here and do other actions based
            // on the response
        }

    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The exception I get is that 我得到的例外是

java.io.FileNotFoundException: content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc: open failed: ENOENT (No such file or directory)

There is file in emulator - test.doc. 模拟器中有一个文件-test.doc。 Is there is any thing I miss in code, please help me. 我在代码中有什么想念的,请帮帮我。 Or suggest a tutorial to upload pdf to php server. 或建议教程将pdf上传到php服务器。

Thanks In Advance. 提前致谢。

Here is the solution of my question: - Here is code of php file - file.php 这是我的问题的解决方案:-这是php文件的代码-file.php

<?php

// DISPLAY FILE INFORMATION JUST TO CHECK IF FILE OR IMAGE EXIST
echo '<pre>';
print_r($_FILES);
echo '</pre>';

// DISPLAY POST DATA JUST TO CHECK IF THE STRING DATA EXIST
echo '<pre>';
print_r($_POST);
echo '</pre>';

$file_path = "images/";
$file_path = $file_path . basename( $_FILES['file']['name']);

if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {

    echo "file saved success";


} else{

   echo "failed to save file";
}?>

Put this file in htdoc folder of Xampp inside test named folder (if there is test folder already then ok, otherwise make a folder named "test"). 将此文件放在Xampp的htdoc文件夹中名为测试的文件夹中(如果已经存在测试文件夹,则确定,否则创建名为“ test”的文件夹)。 And also create a folder named "images", in which uploaded file was saved. 并创建一个名为“ images”的文件夹,其中保存了上传的文件。

Create function to select file from gallery 创建功能以从图库中选择文件

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                1);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(getActivity(), "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

Inside onActivityResult function 内部onActivityResult函数

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedFileURI = data.getData();
            File file = new File(selectedFileURI.getPath().toString());
            Log.d("", "File : " + file.getName());
            uploadedFileName = file.getName().toString();
            tokens = new StringTokenizer(uploadedFileName, ":");
            first = tokens.nextToken();
            file_1 = tokens.nextToken().trim();
            txt_file_name_1.setText(file_1);
        }
    }

This is asyncTask to upload file to server, 这是一个asyncTask,用于将文件上传到服务器,

public class PostDataAsyncTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setCancelable(false);
        pDialog.setMessage("Please wait ...");
        showDialog();
    }

    @Override
    protected String doInBackground(String... strings) {
        try {

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("https://10.0.2.2/test/file.php");

            file1 = new File(Environment.getExternalStorageDirectory(),
                    file_1);
            fileBody1 = new FileBody(file1);

            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("file1", fileBody1);

            httpPost.setEntity(reqEntity);

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null) {
                final String responseStr = EntityUtils.toString(resEntity)
                        .trim();
                Log.v(TAG, "Response: " + responseStr);

            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        hideDialog();
        Log.e("", "RESULT : " + result);

    }
}

Call the asyncTask on button click after selecting the file from gallery. 从图库中选择文件后,在按钮单击上调用asyncTask。

btn_upload.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            new PostDataAsyncTask().execute();

        }
    });

Hope this will help you. 希望这会帮助你。 Happy To Help and Happy Coding. 乐于助人,乐于编码。

The code below is not tested ( as is ) but is generally how one might handle the file upload - there is, as you will see, a debug statement in there. 下面的代码未经测试(按原样),但通常是人们处理文件上传的方式-如您所见,其中有一条调试语句。 Try to send the file and see what you get ~ if all lokks ok, comment out that line and keep your fingers crossed. 尝试发送文件,看看能得到什么〜如果一切顺利,请注释掉该行,并保持双手交叉。

   <?php
        /* Basic file upload handler - untested */
        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_FILES['image'] ) && !empty( $_FILES['image']['tmp_name'] ) ){

            /* Assuming the field being POSTed is called `image`*/
            $name = $_FILES['image']['name'];
            $size = $_FILES['image']['size'];
            $type = $_FILES['image']['type'];
            $tmp  = $_FILES['image']['tmp_name'];


            /* debug:comment out if this looks ok */
            exit( print_r( $_FILES,true ) );

            $result = $status = false;

            $basename=pathinfo( $name, PATHINFO_FILENAME );


            $filepath='http://10.0.2.2/VolleyUpload/'.$basename;

            $result=@move_uploaded_file( $tmp, $filepath );

            if( $result ){
                $sql = "insert into `volleyupload` ( `photo`, `name` ) values ( '$filepath', '$basename' )";
                $status=mysqli_query( $con, $sql );
            }

            echo $result && $status ? 'File uploaded and logged to db' : 'Something not quite right. Uploaded:'.$result.' Logged:'.$status;
        }
    ?>
java.io.FileNotFoundException:  
content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc:
open failed: ENOENT (No such file or directory)

What you have is a content provider path. 您拥有的是内容提供商路径。 Not a file system path. 不是文件系统路径。 So you cannot use the File... classes. 因此,您不能使用File ...类。

Instead use 改为使用

  InputStream is = getContentResolver().openInputStream(uri);

For the rest your php code does not make sense as there is no base64 encoding at upload. 其余的PHP代码没有意义,因为上传时没有base64编码。 Further the $path and $actualpath parameters are not used and confusing. 此外,$ path和$ actualpath参数未使用且令人困惑。 And you did not tell what your script should do. 而且您没有告诉您脚本应该做什么。

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

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