ICode9

精准搜索请尝试: 精确搜索

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

2019-09-30 19:38:04??阅读:583??来源: 互联网

标签:android?php?pdf?file-upload


我卡在那个地方,无法将doc文件发送到php服务器.
我正在使用此代码.

这是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";
}

这是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);
}

我在上传按钮上调用了asynTask.

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

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();
    }
}

我得到的例外是

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

模拟器中有文件 – test.doc.
在代码中是否有任何我想念的东西,请帮助我.
或者建议将pdf上传到php服务器的教程.

提前致谢.

解决方法:

这是我的问题的解决方案: –
这是php文件的代码 – file.php

';
print_r($_FILES);
echo '
'; // DISPLAY POST DATA JUST TO CHECK IF THE STRING DATA EXIST echo '
';
print_r($_POST);
echo '
'; $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"; }?>

将此文件放在测试命名文件夹中的Xampp的htdoc文件夹中(如果已经有测试文件夹,那么确定,否则创建一个名为“test”的文件夹).并创建一个名为“images”的文件夹,其中保存了上传的文件.

创建从库中选择文件的功能

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();
    }
}

在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);
        }
    }

这是asyncTask将文件上传到服务器,

public class PostDataAsyncTask extends AsyncTask {

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

    }
}

从库中选择文件后,在按钮单击时调用asyncTask.

btn_upload.setOnClickListener(new OnClickListener() {

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

        }
    });

希望这会帮助你.
乐意帮助和快乐编码.



标签:android,php,pdf,file-upload

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有