从Android设备在PHP服务器上传文件 [英] Uploading file in php server from android device

查看:194
本文介绍了从Android设备在PHP服务器上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想文件从我的Andr​​oid设备上传到PHP的服务器,但服务器无法接收任何文件。这里是我的示例code,我发现它上线。 PHP的服务器,我上传过块的文件

我的Andr​​oid code

 进口java.io.DataOutputStream中;
进口的java.io.File;
进口java.io.FileInputStream中;
进口java.net.HttpURLConnection中;
进口java.net.MalformedURLException;
进口的java.net.URL;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.database.Cursor;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.net.Uri;
进口android.os.Bundle;
进口android.provider.MediaStore;
进口android.util.Log;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.ImageView;
进口android.widget.TextView;
进口android.widget.Toast;

公共类MainActivity扩展活动实现OnClickListener {

私人TextView中的MessageText;
私人按钮uploadButton,btnselectpic;
私人ImageView的ImageView的;
私人诠释serverResponse code = 0;
私人ProgressDialog对话框= NULL;

私人字符串upLoadServerUri = NULL;
私人字符串的ImagePath = NULL;
@覆盖
公共无效的onCreate(包savedInstanceState){

    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    uploadButton =(按钮)findViewById(R.id.uploadButton);
    =的MessageText(TextView中)findViewById(R.id.messageText);
    btnselectpic =(按钮)findViewById(R.id.button_selectpic);
    ImageView的=(ImageView的)findViewById(R.id.imageView_pic);

    btnselectpic.setOnClickListener(本);
    uploadButton.setOnClickListener(本);
    upLoadServerUri =htt​​p://192.168.2.4/fileupload/Uplo​​adToServer.php;
}


@覆盖
公共无效的onClick(查看为arg0){
    如果(将arg0 == btnselectpic)
    {
        意向意图=新的意图();
        intent.setType(图像/ *);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(原意,用完整的行动),1);
    }
    否则,如果(为arg0 == uploadButton){

         对话框= ProgressDialog.show(MainActivity.this,,上传文件...,真正的);
         messageText.setText(上传开始......);
         新主题(新的Runnable(){
             公共无效的run(){

                  uploadFile(的ImagePath);

             }
           })。开始();
    }

}

@覆盖
保护无效onActivityResult(INT申请code,INT结果code,意图数据){

    如果(要求code == 1安培;&安培;结果code == RESULT_OK){
        //位图的照片=(位图)data.getData()getPath()。

        乌里selectedImageUri = data.getData();
        的ImagePath = getPath(selectedImageUri);
        点阵位图= BitmapFactory.de codeFILE(的ImagePath);
        imageview.setImageBitmap(位);
        messageText.setText(上传文件路径:+的ImagePath);

    }
}
     公共字符串getPath(URI URI){
            的String []投影= {MediaStore.Images.Media.DATA};
            光标光标= managedQuery(URI,投影,NULL,NULL,NULL);
            INT与Column_Index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            返回cursor.getString(Column_Index中);
        }

公众诠释uploadFile(字符串sourceFileUri){


      字符串文件名= sourceFileUri;

      HttpURLConnection的康恩= NULL;
      DataOutputStream类DOS = NULL;
      字符串lineEnd =\ r \ N的;
      串twoHyphens = - ;
      字符串边界=*****;
      INT读取动作,方bytesAvailable,缓冲区大小;
      byte []的缓冲区;
      INT maxBufferSize = 1 * 1024 * 1024;
      文件的SourceFile =新的文件(sourceFileUri);

      如果(!sourceFile.isFile()){

           dialog.dismiss();

           Log.e(一个UploadFile,源文件不存在:+的ImagePath);

           runOnUiThread(新的Runnable(){
               公共无效的run(){
                   messageText.setText(源文件不存在:+的ImagePath);
               }
           });

           返回0;

      }
      其他
      {
           尝试 {

                 //打开一个URL连接到这个Servlet
               的FileInputStream的FileInputStream =新的FileInputStream(的资源文件);
               网址URL =新的URL(upLoadServerUri);

               //打开一个HTTP连接网址
               康恩=(HttpURLConnection类)url.openConnection();
               conn.setDoInput(真正的); //允许输入
               conn.setDoOutput(真正的); //允许输出
               conn.setUseCaches(假); //不要使用缓存副本
               conn.setRequestMethod(POST);
               conn.setRequestProperty(连接,保持活动);
               conn.setRequestProperty(ENCTYPE,多部分/表单数据);
               conn.setRequestProperty(内容类型,多部分/格式数据;边界=+界);
               conn.setRequestProperty(文件,文件名);

               DOS =新DataOutputStream类(conn.getOutputStream());

               dos.writeBytes(twoHyphens +边界+ lineEnd);
               dos.writeBytes(内容处置:表格数据;名称= \文件\文件\
                                         +文件名+\+ lineEnd);

               dos.writeBytes(lineEnd);

               //创建最大大小的缓冲区
               方bytesAvailable = fileInputStream.available();

               BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
               缓冲区=新的字节[BUFFERSIZE]

               //读取文件,并将其写入形式...
               读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);

               而(读取动作大于0){

                 dos.write(缓冲液,0,BUFFERSIZE);
                 方bytesAvailable = fileInputStream.available();
                 BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
                 读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);

                }

               //发送多部分表格数据文件数据后necesssary ...
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);

               从服务器//回应(code和消息)
               serverResponse code = conn.getResponse code();
               串serverResponseMessage = conn.getResponseMessage();

               Log.i(一个UploadFile,HTTP响应是:
                       + serverResponseMessage +:+ serverResponse code);

               如果(serverResponse code == 200){

                   runOnUiThread(新的Runnable(){
                        公共无效的run(){
                            弦乐味精=文件上传已完成\ñ\ñ看到这里上传的文件:\ñ\ N
                                  +C:/ XAMP / htdocs目录/文件上传/上传;
                            messageText.setText(MSG);
                            Toast.makeText(MainActivity.this,文件上传完成。,Toast.LENGTH_SHORT).show();
                        }
                    });
               }

               //关闭流//
               fileInputStream.close();
               dos.flush();
               dos.close();

          }赶上(MalformedURLException的前){

              dialog.dismiss();
              ex.printStackTrace();

              runOnUiThread(新的Runnable(){
                  公共无效的run(){
                      messageText.setText(MalformedURLException的例外情况:检查脚本的网址。);
                      Toast.makeText(MainActivity.thisMalformedURLException的,Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e(上传文件到服务器,错误:+ ex.getMessage(),前);
          }赶上(例外五){

              dialog.dismiss();
              e.printStackTrace();

              runOnUiThread(新的Runnable(){
                  公共无效的run(){
                      messageText.setText(GOT例外:看logcat的);
                      Toast.makeText(MainActivity.this,得到了异常:看到的logcat,Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e(上传文件到服务器异常,异常:+ e.getMessage(),E);
          }
          dialog.dismiss();
          返回serverResponse code;

       } //结束else块
     }}
 

PHP服务器code 在文件上传,我做了通过块文件上传完成后,请人帮我渡过块和相关的Andr​​oid文件上传code

发送正确的code文件上传

 < PHP

如果(空($ _ FILES)|| $ _FILES ['文件'] ['错误']){
死亡({OK:0,信息:无法移动上传的文件}');
}

$块=使用isset($ _ REQUEST [块])? INTVAL($ _ REQUEST [块):0;
$块=使用isset($ _ REQUEST [块])? INTVAL($ _ REQUEST [块):0;

$文件名=使用isset($ _ REQUEST [名称])? $ _REQUEST [名称]:$ _FILES [文件] [名称];
$文件路径=上传/ $文件名;


//打开临时文件
$ OUT = @fopen({$文件路径}。第二部分,$块== 0WB:AB);
// $ OUT2 = @fopen({$文件路径} .part2,$块== 0WB:AB);
如果($出){
//读取二进制输入流,并将其追加到临时文件
在= @fopen $($ _ FILES ['文件'] ['tmp_name的值'],RB);

如果($的){
而($ BUFF = FREAD($中,4096))
      FWRITE($出,$ BUFF);
   //打印($出);
 //回声的sizeof($出);
} 其他
死亡({OK:0,信息:无法打开输入流}');

@fclose($的);

@fclose($出);

@unlink($ _ FILES ['文件'] ['tmp_name的值']);
} 其他
死亡({OK:0,信息:无法打开输出流}');


//检查文件是否已经上传

如果($块|| $块== $块 -  1)
{
//地带的温度。第二部分后缀关闭
重命名({$文件路径}。第二部分,$文件路径);
}


死亡({OK:1,信息:上传成功}');?>
 

解决方案

我不knw生根粉您code BT为您提供两种工作codeS: 这是对所有类型的文件我用了图像的音频和视频文件的

Android的:

 新UploadFileAsync()执行()。



  私有类UploadFileAsync扩展的AsyncTask<字符串,太虚,字符串> {

    @覆盖
    保护字符串doInBackground(字符串... PARAMS){

        尝试 {
  字符串sourceFileUri =/mnt/sdcard/abc.png;

            HttpURLConnection的康恩= NULL;
            DataOutputStream类DOS = NULL;
            字符串lineEnd =\ r \ N的;
            串twoHyphens = - ;
            字符串边界=*****;
            INT读取动作,方bytesAvailable,缓冲区大小;
            byte []的缓冲区;
            INT maxBufferSize = 1 * 1024 * 1024;
            文件的SourceFile =新的文件(sourceFileUri);

            如果(sourceFile.isFile()){

                尝试 {
                    字符串upLoadServerUri =htt​​p://website.com/abc.php?;

                    //打开一个URL连接到这个Servlet
                    的FileInputStream的FileInputStream =新的FileInputStream(
                            源文件);
                    网址URL =新的URL(upLoadServerUri);

                    //打开一个HTTP连接网址
                    康恩=(HttpURLConnection类)url.openConnection();
                    conn.setDoInput(真正的); //允许输入
                    conn.setDoOutput(真正的); //允许输出
                    conn.setUseCaches(假); //不要使用缓存副本
                    conn.setRequestMethod(POST);
                    conn.setRequestProperty(连接,保持活动);
                    conn.setRequestProperty(ENCTYPE
                            多部分/表单数据);
                    conn.setRequestProperty(内容类型,
                            的multipart / form-data的;边界=+界);
                    conn.setRequestProperty(条例,sourceFileUri);

                    DOS =新DataOutputStream类(conn.getOutputStream());

                    dos.writeBytes(twoHyphens +边界+ lineEnd);
                    dos.writeBytes(内容处置:表格数据;名称= \法案\;文件名= \
                            + sourceFileUri +\+ lineEnd);

                    dos.writeBytes(lineEnd);

                    //创建最大大小的缓冲区
                    方bytesAvailable = fileInputStream.available();

                    BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
                    缓冲区=新的字节[BUFFERSIZE]

                    //读取文件,并将其写入形式...
                    读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);

                    而(读取动作大于0){

                        dos.write(缓冲液,0,BUFFERSIZE);
                        方bytesAvailable = fileInputStream.available();
                        BUFFERSIZE =数学
                                .min(方bytesAvailable,maxBufferSize);
                        读取动作= fileInputStream.read(缓冲液,0,
                                BUFFERSIZE);

                    }

                    //文件后,发送多部分的表单数据necesssary
                    // 数据...
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens +边界+ twoHyphens
                            + lineEnd);

                    从服务器//回应(code和消息)
                    serverResponse code = conn.getResponse code();
                    字符串serverResponseMessage =康恩
                            .getResponseMessage();

                    如果(serverResponse code == 200){

                        // messageText.setText(MSG);
                        //Toast.makeText(ctx,文件上传完成。,
                        // Toast.LENGTH_SHORT).show();

                        // recursiveDelete(mDirectory1);

                    }

                    //关闭流//
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                }赶上(例外五){

                    // dialog.dismiss();
                    e.printStackTrace();

                }
                // dialog.dismiss();

            } //结束else块


        }赶上(例外前){
            // dialog.dismiss();

            ex.printStackTrace();
        }
        返回已执行;
    }

    @覆盖
    保护无效onPostExecute(字符串结果){

    }

    @覆盖
    在preExecute保护无效(){
    }

    @覆盖
    保护无效onProgressUpdate(空...值){
    }
}
 

PHP ::

 < PHP


     如果(is_uploaded_file($ _ FILES ['法案'] ['tmp_name的值'])){
    $ uploads_dir =./;
                            $ tmp_name的值= $ _FILES ['法案'] ['tmp_name的值'];
                            $ pic_name = $ _FILES ['法案'] ['名称'];
                            move_uploaded_file($ tmp_name的值,$ uploads_dir $ pic_name。);
                            }
               其他{
                   回声文件没有上传成功。
           }

   ?>
 

I am trying to upload file to a php server from my android device but server is not receiving any file. here is my sample code, I found it on-line. php server , I am uploading a file through chunk

My Android code

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;

private String upLoadServerUri = null;
private String imagepath=null;
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    uploadButton = (Button)findViewById(R.id.uploadButton);
    messageText  = (TextView)findViewById(R.id.messageText);
    btnselectpic = (Button)findViewById(R.id.button_selectpic);
    imageview = (ImageView)findViewById(R.id.imageView_pic);

    btnselectpic.setOnClickListener(this);
    uploadButton.setOnClickListener(this);
    upLoadServerUri = "http://192.168.2.4/fileupload/UploadToServer.php";
}


@Override
public void onClick(View arg0) {
    if(arg0==btnselectpic)
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
    }
    else if (arg0==uploadButton) {

         dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
         messageText.setText("uploading started.....");
         new Thread(new Runnable() {
             public void run() {

                  uploadFile(imagepath);

             }
           }).start();     
    }

} 

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1 && resultCode == RESULT_OK) {
        //Bitmap photo = (Bitmap) data.getData().getPath(); 

        Uri selectedImageUri = data.getData();
        imagepath = getPath(selectedImageUri);
        Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
        imageview.setImageBitmap(bitmap);
        messageText.setText("Uploading file path:" +imagepath);

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

public int uploadFile(String sourceFileUri) {


      String fileName = sourceFileUri;

      HttpURLConnection conn = null;
      DataOutputStream dos = null;  
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024; 
      File sourceFile = new File(sourceFileUri); 

      if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"+imagepath);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"+ imagepath);
               }
           }); 

           return 0;

      }
      else
      {
           try { 

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);

               // Open a HTTP  connection to  the URL
               conn = (HttpURLConnection) url.openConnection(); 
               conn.setDoInput(true); // Allow Inputs
               conn.setDoOutput(true); // Allow Outputs
               conn.setUseCaches(false); // Don't use a Cached Copy
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Connection", "Keep-Alive");
               conn.setRequestProperty("ENCTYPE", "multipart/form-data");
               conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
               conn.setRequestProperty("file", fileName); 

               dos = new DataOutputStream(conn.getOutputStream());

               dos.writeBytes(twoHyphens + boundary + lineEnd); 
               dos.writeBytes("Content-Disposition: form-data; name=\"file\";file\""
                                         + fileName + "\"" + lineEnd);

               dos.writeBytes(lineEnd);

               // create a buffer of  maximum size
               bytesAvailable = fileInputStream.available(); 

               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               buffer = new byte[bufferSize];

               // read file and write it into form...
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

               while (bytesRead > 0) {

                 dos.write(buffer, 0, bufferSize);
                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                }

               // send multipart form data necesssary after file data...
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

               // Responses from the server (code and message)
               serverResponseCode = conn.getResponseCode();
               String serverResponseMessage = conn.getResponseMessage();

               Log.i("uploadFile", "HTTP Response is : "
                       + serverResponseMessage + ": " + serverResponseCode);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                  +" c:/xamp/htdocs/file upload/uploads";
                            messageText.setText(msg);
                            Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

               //close the streams //
               fileInputStream.close();
               dos.flush();
               dos.close();

          } catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

       } // End else block 
     }}

PHP Server code in file uploading ,I am done file uploading done through chunk ,please anyone help me send right code file uploading through chunk and relevant android file uploading code

<?php

if (empty($_FILES) || $_FILES['file']['error']) {
die('{"OK": 0, "info": "Failed to move uploaded file."}');
}

$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;

$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = "uploads/$fileName";


// Open temp file
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
//$out2 = @fopen("{$filePath}.part2", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = @fopen($_FILES['file']['tmp_name'], "rb");

if ($in) {
while ($buff = fread($in, 4096))
      fwrite($out, $buff);
   //print($out);
 // echo sizeof($out);
} else
die('{"OK": 0, "info": "Failed to open input stream."}');

@fclose($in);

@fclose($out);

@unlink($_FILES['file']['tmp_name']);
} else
die('{"OK": 0, "info": "Failed to open output stream."}');


// Check if file has been uploaded

if (!$chunks || $chunk == $chunks - 1)
{
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}


die('{"OK": 1, "info": "Upload successful."}');?>

解决方案

i dont knw abt your code bt providing you both working codes: this is for all types of files i used it for image audio and for video files

Android:

new UploadFileAsync().execute("");



  private class UploadFileAsync extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        try {
  String sourceFileUri = "/mnt/sdcard/abc.png";

            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            File sourceFile = new File(sourceFileUri);

            if (sourceFile.isFile()) {

                try {
                    String upLoadServerUri = "http://website.com/abc.php?";

                    // open a URL connection to the Servlet
                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);
                    URL url = new URL(upLoadServerUri);

                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true); // Allow Inputs
                    conn.setDoOutput(true); // Allow Outputs
                    conn.setUseCaches(false); // Don't use a Cached Copy
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("ENCTYPE",
                            "multipart/form-data");
                    conn.setRequestProperty("Content-Type",
                            "multipart/form-data;boundary=" + boundary);
                    conn.setRequestProperty("bill", sourceFileUri);

                    dos = new DataOutputStream(conn.getOutputStream());

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
                            + sourceFileUri + "\"" + lineEnd);

                    dos.writeBytes(lineEnd);

                    // create a buffer of maximum size
                    bytesAvailable = fileInputStream.available();

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];

                    // read file and write it into form...
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                    while (bytesRead > 0) {

                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math
                                .min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0,
                                bufferSize);

                    }

                    // send multipart form data necesssary after file
                    // data...
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens
                            + lineEnd);

                    // Responses from the server (code and message)
                    serverResponseCode = conn.getResponseCode();
                    String serverResponseMessage = conn
                            .getResponseMessage();

                    if (serverResponseCode == 200) {

                        // messageText.setText(msg);
                        //Toast.makeText(ctx, "File Upload Complete.",
                        //      Toast.LENGTH_SHORT).show();

                        // recursiveDelete(mDirectory1);

                    }

                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                } catch (Exception e) {

                    // dialog.dismiss();
                    e.printStackTrace();

                }
                // dialog.dismiss();

            } // End else block


        } catch (Exception ex) {
            // dialog.dismiss();

            ex.printStackTrace();
        }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

PHP::

 <?php


     if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
    $uploads_dir = './';
                            $tmp_name = $_FILES['bill']['tmp_name'];
                            $pic_name = $_FILES['bill']['name'];
                            move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
                            }
               else{
                   echo "File not uploaded successfully.";
           }

   ?>

这篇关于从Android设备在PHP服务器上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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