Android上传文件到Web服务器,PHP接收文件(一)


  1. php服务器


<?php  
    $target_path  = "./upload1/";//接收文件目录  
    $target_path = $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'];  
    }  
?>

 

2.android客户端

    总共4步:设置http请求:http头---http正文---发送http请求---返回服务器结果

    待解决:只能上传小文件。文件名中不能有中文。

package com.tianlei.httpUrlConnection_PHPUpload;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Uploadfile{
	// 要上传的文件路径,理论上可以传输任何文件,实际使用时根据需要处理
	//private String uploadFile = "/sdcard/testimg.jpg";
	//private String srcPath = "/sdcard/testimg.jpg";
	  private String srcPath;
	// 服务器上接收文件的处理页面,这里根据需要换成自己的
	private String actionUrl = "http://120.126.16.52/uploadfile.php";
	private Context c;
	public Uploadfile(Context c, String filepath){
		this.c = c;
		this.srcPath = filepath;
	}

	/* 上传文件至Server,uploadUrl:接收文件的处理页面 */
	public void uploadFile(){
		String uploadUrl = actionUrl;
		String end = "\r\n";
		String twoHyphens = "--";  //每个字段用“--”分隔 
		String boundary = "******";//在HTTP请求头设置一个分隔符
		try{
			URL url = new URL(uploadUrl);//建立url
			/*打开url连接
			* 此处的urlConnection对象实际上是根据URL的 请求协议(此处是http)生成的URLConnection类
			* 的子类HttpURLConnection,故此处最好将其转化为HttpURLConnection类型的对象,
			* 以便用到HttpURLConnection更多的API*/
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			  
			/*http头
			 * 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃,此方法用于在预先不知道内容长度时启用,
			 * 没有进行内部缓冲的 HTTP 请求正文的流。*/
			//httpURLConnection.setChunkedStreamingMode(256 * 1024);// 256K
			httpURLConnection.setConnectTimeout(10 * 60 * 1000);
			// 允许输入输出流
			httpURLConnection.setDoInput(true);// 设置是否从httpUrlConnection读入,默认情况下是true
			/*设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 
			http正文内,因此需要设为true, 默认情况下是false*/
			httpURLConnection.setDoOutput(true);
			// Post 请求不能使用缓存
			httpURLConnection.setUseCaches(false);//没有进行内部缓冲
			// 设定请求的方法为"POST",默认是GET
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			//首先在HTTP请求头设置一个分隔符*****
			httpURLConnection.setRequestProperty("Content-Type",
			"multipart/form-data;boundary=" + boundary);
			//httpURLConnection.connect(); // 连接
			  
			/*http请求的正文
			* 正文的内容是通过outputStream流写入的
			* 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, 
			     所以在开发中不调用上述的connect()也可以)。*/
			
			DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
			//每个字段用“--”分隔
			dos.writeBytes(twoHyphens + boundary + end);
			/*srcPath.substring(srcPath.lastIndexOf("/") + 1):表示文件名字
			 */
			dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
					+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
					+ "\""+ end);
			dos.writeBytes(end);
	  
			//上传的文件的内容
			FileInputStream fis = new FileInputStream(srcPath);
			byte[] buffer = new byte[8192]; // 8k
			int count = 0;
			// 读取文件
			while ((count = fis.read(buffer)) != -1){
			dos.write(buffer, 0, count);
			}
			fis.close();
			//设置分隔符
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();
	
			//发送请求
			// 在调用下边的getInputStream()函数时才将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。 
			InputStream is = httpURLConnection.getInputStream();
			//至此,http请求已经被发送到服务器
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			//BufferedReader br = new BufferedReader(new InputStreamReader
			//		  (httpURLConnection.getInputStream(),"utf-8"));
			      
			/*获取返回结果.
			 * 在getInputStream()函数调用的时候,就会把准备好的http请求 正式发送到服务器了,
			 * 然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。*/
			String result = br.readLine();
			Toast.makeText(c, result, Toast.LENGTH_SHORT).show();
			dos.close();
			is.close();
			}catch (Exception e){
				e.printStackTrace();
				//setTitle(e.getMessage());
				Toast.makeText(c, e.getMessage(), Toast.LENGTH_SHORT).show(); 
			}
		}
}

转载于:https://my.oschina.net/u/1014520/blog/194549

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值