Android上传文件 服务器端采用php

Android客户段代码

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;



public class MainActivity extends Activity {
	private final String TAG = "upload";
    private String newName ="test.jpg";
    private String uploadFile ="/sdcard/test.jpg";
    private String actionUrl ="";
    private StringBuffer b;
    private Button mButton;
    
    private Handler handler = new Handler();
    @Override
      public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        /* 设置mButton的onClick事件处理 */    
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v)
          {
        	  
        	  new Thread(new Runnable(){

				@Override
				public void run() {
					Looper.prepare();
					// TODO Auto-generated method stub
					uploadFile();
					Looper.loop();
				}
        		  
        	  }).start();
            
          }
        });
      }
      /* 上传文件至Server的方法 */
      private void uploadFile()
      {
    	  Log.i(TAG, "in function");
    	  
        String end ="\r\n";
        String twoHyphens ="--";
        String boundary ="*****";
        try
        {
        	Log.i(TAG, "in try");
//        	Toast.makeText(getApplicationContext(), "in try", Toast.LENGTH_SHORT).show();
          URL url =new URL(actionUrl);
          HttpURLConnection con=(HttpURLConnection)url.openConnection();
          Log.i(TAG, "connection");
          /* 允许Input、Output,不使用Cache */
          con.setDoInput(true);
          con.setDoOutput(true);
          con.setUseCaches(false);
          /* 设置传送的method=POST */
          con.setRequestMethod("POST");
          con.setConnectTimeout(5000);
          /* setRequestProperty */
          con.setRequestProperty("Connection", "Keep-Alive");
          con.setRequestProperty("Charset", "UTF-8");
          con.setRequestProperty("Content-Type",
                             "multipart/form-data;boundary="+boundary);
          /* 设置DataOutputStream */
          Log.i(TAG, "before write");
          
         
          DataOutputStream ds =
            new DataOutputStream(con.getOutputStream());
          ds.writeBytes(twoHyphens + boundary + end);
          ds.writeBytes("Content-Disposition: form-data; "+
                        "name=\"uploadedfile\";filename=\""+
                        newName +"\""+ end);
          ds.writeBytes(end); 
          Log.i(TAG, "after write");
//          Toast.makeText(getApplicationContext(), "after write", Toast.LENGTH_SHORT).show();
          /* 取得文件的FileInputStream */
          FileInputStream fStream =new FileInputStream(uploadFile);
          /* 设置每次写入1024bytes */
          int bufferSize =1024;
          byte[] buffer =new byte[bufferSize];
          int length =-1;
          /* 从文件读取数据至缓冲区 */
          while((length = fStream.read(buffer)) !=-1)
          {
            /* 将资料写入DataOutputStream中 */
            ds.write(buffer, 0, length);
          }
          ds.writeBytes(end);
          ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
          /* close streams */
          fStream.close();
          ds.flush();
          /* 取得Response内容 */
          InputStream is = con.getInputStream();
          int ch;
          b =new StringBuffer();
          while( ( ch = is.read() ) !=-1 )
          {
            b.append( (char)ch );
          }
          /* 将Response显示于Dialog */
          handler.post(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				showDialog("上传成功"+b.toString().trim());
			}
        	  
          });
          
          /* 关闭DataOutputStream */
          ds.close();
        }
        catch(final Exception e)
        {
        	handler.post(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					showDialog("上传失败"+e);
				}
        		
        	});
//          showDialog("上传失败"+e);
        }
      }
      /* 显示Dialog的method */
      private void showDialog(String mess)
      {
        new AlertDialog.Builder(MainActivity.this).setTitle("Message")
         .setMessage(mess)
         .setNegativeButton("确定",new DialogInterface.OnClickListener()
         {
           public void onClick(DialogInterface dialog, int which)
           {          
           }
         })
         .show();
      }

服务器端php代码
<pre class="php" name="code"><?php

$target_path = basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
   echo "The file ".  basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}  else{
   echo "There was an error uploading the file, please try again!" . $_FILES['uploadedfile']['error'];
}


?>

网上找了许多,但或多或少的都有一些错误
Android客户端中的上传路径可以写外部的服务器的地址,比如租用的阿里云的服务器等,也可以自己本地搭建一个apache服务器,但注意,本地一定要关闭防火墙,否则Android客户端连不上

另外,在Android客户端中,文件的操作,要单独放在一个进程里面,并加入looper.prepare()方法,不然报错!!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值