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

标签 php android 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();
    }
}

我得到的异常(exception)是

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

<?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";
}?>

将此文件放在 Xampp 的 htdoc 文件夹中,在名为 test 的文件夹中(如果已经有 test 文件夹,则可以,否则创建一个名为“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<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);

    }
}

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

btn_upload.setOnClickListener(new OnClickListener() {

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

        }
    });

希望对您有所帮助。 乐于助人,乐于编码。

关于php - 将 doc、pdf、xls 等从 android 应用程序上传到 php 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820723/

相关文章:

php - 在 PHP-CLI 中相当于 $_ENV ['APACHE_RUN_USER' ]

php - 如何在 PHP 中拆分字符串中的泰米尔语字符

php - 如何在一个选项卡或窗口中更新最新的 ID,同时在不同的选项卡或窗口中插入记录?

android - 如何撤消使用 Room 持久库所做的删除?

javascript - 如何在 Node js中创建pdf文件

javascript - 获取嵌入式pdf的当前页码

php - 使用 symfony 配置树生成器创建多维数组

android - 在 Android 设备中运行 IONIC 2 应用程序时出现问题

android - Android 项目无法在 Page Indicator 和 CirclePageIndicator 上运行

javascript - 将js库包含到pdf中