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


  1. php服务器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客户端java

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

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

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(); 
			}
		}
}
相关文章
相关标签/搜索