Android酱油笔记之上传文件到php web


1.搭建LAMP环境

2.upload_file.php源码如下

<?php
	$file_path = "/var/test/upload/";
	if ((($_FILES["file"]["type"] == "image/gif")
		|| ($_FILES["file"]["type"] == "image/jpeg")
		|| ($_FILES["file"]["type"] == "image/pjpeg"))
		&& ($_FILES["file"]["size"] < 20000))
  	{
  		if ($_FILES["file"]["error"] > 0){
    			echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    		}else{
    			echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    			echo "Type: " . $_FILES["file"]["type"] . "<br />";
    			echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    			echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    			if (file_exists($file_path . $_FILES["file"]["name"])){
      				echo $_FILES["file"]["name"] . " already exists. ";
      			}else{
      				move_uploaded_file($_FILES["file"]["tmp_name"],$file_path . $_FILES["file"]["name"]);
      				echo "Stored in: " . $file_path . $_FILES["file"]["name"];
      			}
    		}
  	}else{
  		echo "Invalid file";
  	}
?>

3.Android端源码如下

package com.others.php;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class TestPHPUploadActivity extends Activity{

	private String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/gxtest";
	private TextView textView;
	private Button button;
	private String uploadUrl = "http://192.168.1.106/upload_file.php";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		File dir = new File(filePath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		File file = new File(filePath+"/wer.jpg");
		if(!file.exists()){
			try {
				InputStream is = getAssets().open("wer.jpg");
				FileOutputStream out = new FileOutputStream(filePath+"/wer.jpg");
				byte[] buffer = new byte[1024];
				int len;
				while((len = is.read(buffer))!=-1)
				{
					out.write(buffer, 0, len);
				}
				out.flush();
				is.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		filePath = filePath+"/wer.jpg";
		
		LinearLayout lin = new LinearLayout(this);
		lin.setOrientation(LinearLayout.VERTICAL);
		textView = new TextView(this);
		textView.setText("文件路径:"+ filePath);
		lin.addView(textView);
		
		button = new Button(this);
		button.setText("开始上传");
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						uploadFile(uploadUrl, filePath);
					}
				}).start();
			}
		});
		lin.addView(button);
		
		setContentView(lin);
	}
	
	 /* 上传文件至Server,uploadUrl:接收文件的处理页面 */  
	private void uploadFile(String uploadUrl,String filePath)
	{  
		String end = "\r\n";
		String sepa1 = "--";
		String sepa2 = "--";
		String sepa = sepa1+sepa2;
		String identity = Math.random()+"";
		try{  
			URL url = new URL(uploadUrl);  
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();    
			httpURLConnection.setChunkedStreamingMode(10 * 1024);// 10K  
			// 允许输入输出流  
			httpURLConnection.setDoInput(true);  
			httpURLConnection.setDoOutput(true);  
			httpURLConnection.setUseCaches(false);  
			// 使用POST方法  
			httpURLConnection.setRequestMethod("POST");  
			httpURLConnection.setRequestProperty("Content-Type"," multipart/form-data; boundary="+sepa1+identity);
			DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());  
			dos.writeBytes(sepa+identity+end);  
			dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"wer.jpg\"" + end);  
			dos.writeBytes("Content-Type: image/pjpeg" + end);
			dos.writeBytes(end);  
			FileInputStream fis = new FileInputStream(filePath);  
			byte[] buffer = new byte[1024]; // 1k  
			int count = 0;  
			// 读取文件  
			while ((count = fis.read(buffer)) != -1)  
			{  
				httpURLConnection.getOutputStream().write(buffer, 0, count);  
			} 
			fis.close();  

			dos.writeBytes(end); 
			dos.writeBytes(sepa+identity+end);
			dos.writeBytes("Content-Disposition: form-data; name=\"submit\"" + end);
			dos.writeBytes("Submit" +end);
			dos.writeBytes(sepa+identity+sepa2+end);  
			httpURLConnection.getOutputStream().flush();  

			InputStream is = httpURLConnection.getInputStream();  
			InputStreamReader isr = new InputStreamReader(is, "utf-8");  
			BufferedReader br = new BufferedReader(isr);  
			String result = br.readLine();  

			Bundle b = new Bundle();
			b.putString("value", result);
			Message mes = new Message();
			mes.setData(b);
			handler.sendMessage(mes);

			httpURLConnection.getOutputStream().close();  
			is.close();  

		} catch (Exception e)  {  
			  e.printStackTrace();
		}  
	 }  
	
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			String result = msg.getData().getString("value");
			Toast.makeText(TestPHPUploadActivity.this, result, Toast.LENGTH_LONG).show(); 
		}
	};
	 
}

4.另外,你也可以利用html形式抓包实现,html代码如下

<form action="upload_file.php" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>


5.其他事项可参考HTTP的相关协议,如果不足之处,劳架指出,谢谢


注意:

1.Android端需要权限如下

<uses-permission android:name="android.permission.INTERNET"/>

2.web端需要留意上传所在目录的权限

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值