上传doc,pdf,xls等从android应用程序到php服务器 [英] Upload doc, pdf,xls etc, from android application to php server

查看:135
本文介绍了上传doc,pdf,xls等从android应用程序到php服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我卡在那个地方,无法发送DOC文件到PHP服务器。
我正在使用这个代码。

这里是PHP代码。


$ b

  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));
回显成功上传;
}

mysqli_close($ con);
} else {
echoError;

$ / code $ / pre

这里是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();
PostDataAsyncTask()。execute();





doInBackground中的函数调用是

  private void postFile(){
try {

//要发布的文件
String textFile = Environment。 getExternalStorageDirectory()
+/ Woodenstreet Doc.doc;
Log.v(TAG,textFile:+ textFile);

//文件发布的URL
字符串postReceiverUrl =http://10.0.2.2/VolleyUpload/upload.php;
Log.v(TAG,postURL:+ postReceiverUrl);

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

//发帖头
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);

//执行HTTP发布请求
HttpResponse响应= httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

if(resEntity!= null){

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

//你可以在这里添加一个if语句,并根据
//执行其他操作
}

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


$ / code $ / pre
$ b $ p我得到的例外是

  java.io.FileNotFoundException:content:/com.topnet999.android.filemanager/storage/0F02-250A/test.doc:打开失败:ENOENT (没有这样的文件或目录)

仿真器中有文件test.doc。
是否有任何我想念的代码,请帮助我。
或建议上传PDF到PHP服务器的教程。



在此之前感谢。

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

 <?php 

//显示文件信息只需检查文件或图像是否存在
echo'< pre>;
print_r($ _ FILES);
echo'< / pre>';

//显示POST数据只是检查字符串数据是否存在
echo'< pre>;
print_r($ _ POST);
echo'< / pre>';

$ file_path =images /;
$ file_path = $ file_path。 basename($ _FILES ['file'] ['name']);
$ b $ if(move_uploaded_file($ _ FILES ['file'] ['tmp_name'],$ file_path)){

echofile saved success;


} else {

echo保存文件失败;
}?>

将这个文件放入测试命名文件夹内的Xampp的htdoc文件夹中(如果已经有测试文件夹, ,否则建立一个名为test的文件夹)。创建一个名为images的文件夹,其中保存了上传的文件。



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

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

尝试{
startActivityForResult(
Intent.createChooser(intent,Select a File to Upload),
1);
catch(android.content.ActivityNotFoundException ex){
Toast.makeText(getActivity(),请安装一个文件管理器。,
Toast.LENGTH_SHORT).show();


$ / code $ / $ p

里面的onActivityResult函数

  @Override 
public void onActivityResult(int requestCode,int resultCode,Intent data){
// TODO自动生成的方法存根
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);




$ b这是asyncTask将文件上传到服务器, p>

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

保护void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage(Please wait ...);
showDialog();

$ b $覆盖
保护字符串doInBackground(字符串...字符串){
尝试{

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

file1 =新建文件(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);


$ b} catch(NullPointerException e){
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
返回null;


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






$ b

调用asyncTask on按钮后点击

  btn_upload.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v){
PostDataAsyncTask()。execute();
$ b}
});

希望这会对您有所帮助。
快乐帮助和快乐编码。

I get stuck at that place and unable to send doc file to php server. I am using this code.

Here is PHP code.

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

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.

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

A function calls in doInBackground is

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. Is there is any thing I miss in code, please help me. Or suggest a tutorial to upload pdf to php server.

Thanks In Advance.

解决方案

Here is the solution of my question: - Here is code of php file - 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"). And also create a folder named "images", in which uploaded file was saved.

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

@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,

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.

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.

这篇关于上传doc,pdf,xls等从android应用程序到php服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆