Home  >  Article  >  php教程  >  android原生POST、httpClient4.X实现向PHP服务器上传文件

android原生POST、httpClient4.X实现向PHP服务器上传文件

WBOY
WBOYOriginal
2016-06-06 19:55:301361browse

前言:虽然网上代码一堆,相对减轻了尝试的复杂程度,但真正运行起来还是有各种问题的,没有源码直接运行是一个很大问题,我尝试了一天之后,终于弄懂了些门路,分享给大家,对于原生POST方式上传,因为我也不会用这种方式上传文件,效率低,不好用,所以我

前言:虽然网上代码一堆,相对减轻了尝试的复杂程度,但真正运行起来还是有各种问题的,没有源码直接运行是一个很大问题,我尝试了一天之后,终于弄懂了些门路,分享给大家,对于原生POST方式上传,因为我也不会用这种方式上传文件,效率低,不好用,所以我也没有深究具体代码及原理,但我给出的代码是可行的,我们先从PHP在浏览器中上传图片到服务器开始,然后逐步讲解通过android是如何上传的,android的那些参数该如何构造。

一、通过网页上传图片到PHP服务器

具体讲解参考我这篇文章《不刷新实现图片上传功能》,里面源码啥啥的都有,下面我只贴出前后台部分代码,讲解一个问题

前台部分代码:

<div id="upLoad">
	<div id="processing" style="font-size:10px;"></div>
	<form action="post2.php" method="post" enctype="multipart/form-data" target="form-target" onsubmit="startUpload();">
		<tr>
			<td><span>上传到图库</span></td>
			<td><input type="file" name="upfile" id="file" style="margin-left:10px"></td>
			<td><input type="submit" value="上传" style="margin-left:25px;padding-left:5px;padding-right:5px;"></td>
		</tr>
	</form>
<iframe style="width:0; height:0; border:0;" name="form-target"></iframe>
</div>

注意一个input控件type='file',name='upfile'

后台部分代码

$filePath="temp/";
if (!file_exists($filePath)){//如果指定文件夹不存在,则创建文件夹
            mkdir($filePath , 0777);
     }
//重新定义文件路径及文件名
//分离文件路径,分离结果为:pathinfo() 返回一个关联数组包含有 path 的信息。包括以下的数组单元:dirname,basename 和 extension。
$houzhui = pathinfo($_FILES['upfile']['name']);
//判断格式是否是图片格式
if ( !in_array($houzhui['extension'],array('jpg','gif','png','JPG','GIF','PNG')) ) {
	$result=2;
}else{
	$name=$filePath."newName".'.'.$houzhui['extension'];
	//移动上传的临时文件,为新的文件
	//如果移动成功,输出相应内容
	if(move_uploaded_file($_FILES['upfile']['tmp_name'],$name))
	{
		$result=0;
	}
	//如果移动失败
	else{
		$result=-1;
	}
}

这里注意一个变量:$_FILES['upfile']['name'],$_FILES的第一个参数是upfile,表示就是接收我们上面定义的 ,所传上来的文件

二、android原生POST上传文件

基本用不到,不细讲了,直接看源码吧(源码在最后)

三、httpClient 4.X实现向PHP服务器上传文件

上效果图:

android原生POST、httpClient4.X实现向PHP服务器上传文件

android端:

/* 上传文件至Server,uploadUrl:接收文件的处理页面 */
private void uploadFile(String uploadUrl) throws Exception
{
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpPost httppost = new HttpPost(uploadUrl);
		
		MultipartEntity entity = new MultipartEntity();
		
		File file = new File(srcPath);
		FileBody fileBody = new FileBody(file);
		entity.addPart("uploadedfile", fileBody);
			
		httppost.setEntity(entity);
		HttpResponse response = httpclient.execute(httppost);
		
		HttpEntity resEntity = response.getEntity();
		if (resEntity != null) {			
			Toast.makeText(this, EntityUtils.toString(resEntity), Toast.LENGTH_LONG).show();
		}

		httpclient.getConnectionManager().shutdown();

}
这里注意一下这小段代码:
MultipartEntity entity = new MultipartEntity();		
File file = new File(srcPath);
FileBody fileBody = new FileBody(file);
entity.addPart("uploadedfile", fileBody);		
httppost.setEntity(entity);

2、下句:entity.addPart("uploadedfile", fileBody);这句,把我们的fileBody加入到表单中,而前面的uploadedfile就相当于input type=file name='xxx'的name字段的值,这就是为什么在PHP接收中,$_FILES['uploadedfile']['name'],这个$_FILES第一个参数要与entity.addPart("uploadedfile", fileBody);的第一个参数一样的原因;

看服务器端(PHP):

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

难度不大,只注意一点:$_FILES['uploadedfile']['tmp_name']的第一个参数要与android代码中的entity.addPart("uploadedfile", fileBody);第一个参数名保持一致;
在源码中,这对这种方法稍微进行了扩充,同时上传两个图片到PHP服务器;


上源码啦:http://download.csdn.net/detail/harvic880925/6769671(不要分,仅供分享)

实例运行方法:

1、使用真机测试,使服务器与真机处于同一局域网中;
2、将Desert.jpg和1.jpg复制到手机sdcard根目录下,即Desert.jpg所处的位置为:sdcard/Desert.jpg和sdcard/1.jpg;
3、将receive_file.php,放在Apache服务器htdocs目录下;
4、将android代码中的:222.195.151.19,改成自己电脑PHP服务器的地址;


http://blog.csdn.net/harvic880925/article/details/17565481

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn