Home Backend Development PHP Tutorial android上传图片到PHP后台全过程

android上传图片到PHP后台全过程

Jun 23, 2016 pm 01:29 PM

PS:便宜的服务器可是会不定时的坑你一把。     

今天在修改app的一些交互以及重构代码。一切都是那么顺利,啪啪啪,runing,测试没问题,再啪啪啪。。。

突然,测试上传头像的时候,老是连接超时。。。。报如下错误:

XXXXXXSokcetTimeOutXXXXXXXX

然后自己设置HTTP的超时时间:

  //设置超时时间  httpclient.setTimeout(20000);
Copy after login

再building,runing,还是不行。。。。这就怪了,明明好好的,怎么会突然就变成连接超时了呢!又折腾了一阵子后,也跟后台那边的朋友沟通过,他也测试了上传接口,发现没什么问题,就让我自己去折腾去了。。。。

我就郁闷了,看不出原先的代码有什么错误,也没什么法子了,就出最下下策吧,自己搭一个PHP上传图片接口,亲自测试下到底是怎么回事。。。。


1.首先,你得下一个方便快捷的PHP服务器,我这里用了WampServer,百度----下载-----安装-----启动,浏览器输入:http://127.0.0.1 有页面显示,OK了。就这么简单!

2.浏览器输入 : http://本机IP地址    回车,   发现报错,类似“You don't have permission to access / on this server”  说明你的WM还没设置,需要进行如下设置:

造成这个问题的原因是Apache 的http.conf内的默认配置是
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
只允许127.0.0.1访问,点击wampserver图标让后点击Putonline,http.conf内的以上默认配置自动修改为
# onlineoffline tag - don't remove
Order Allow,Deny
Allow from all
现在localhost可以访问了。

同样phpMyadmin在localhost下不能正常访问在127.0.0.1能正常访问,解决方法:
点击根目录下的alias目录,打开phpmyadmin.conf配置文件,和上面修改http.conf一样把
Deny from all
Allow from 127.0.0.1
修改为
Allow from all


3. 再此输入 : http://本机IP地址    回车    显示页面    OK!   至于为什么要第二步、第三步呢,我就不说了。。。留给新人去想想吧! 大神直接无视。。。。。

4.写一个上传图片的PHP文件,当然我一个敲java的孩子一下子怎么可能憋的出来,那怎么办,当然是百度参考别人的了,下面的PHP代码源自网络,亲测没有错误:

<?php $base_path = "./upload/"; //存放目录if(!is_dir($base_path)){    mkdir($base_path,0777,true);}$target_path = $base_path . basename ( $_FILES ['attach'] ['name'] );if (move_uploaded_file ( $_FILES ['attach'] ['tmp_name'], $target_path )) {	$array = array (			"status" => true,			"msg" => $_FILES ['attach'] ['name'] 	);	echo json_encode ( $array );} else {	$array = array (			"status" => false,			"msg" => "There was an error uploading the file, please try again!" . $_FILES ['attach'] ['error'] 	);	echo json_encode ( $array );}?>
Copy after login

5.将上面的php文件放在WM安装目录下的www目录下,我的如下图所示,仅供参考:




6.经过上面几个步骤,PHP端已经搭建好了,现在就是回到android端改改IP地址测试下就oK了,代码段如下:

	       //HTTP上传图片		RequestParams params = new RequestParams();		try {			//将压缩后的bitmap保存为图片文件			String saveImgPath=getSD_Path()+"/saveimg.png";			File saveimg=new File(saveImgPath);			FileOutputStream fos = new FileOutputStream(saveimg);			bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);			fos.flush();			fos.close();			//上传压缩后的文件,大约100k左右			File uploadImg=new File(saveImgPath);			<span style="color:#ff0000;">params.put("attach", uploadImg);</span>		} catch (FileNotFoundException e) {			e.printStackTrace();		} catch (IOException e) {			e.printStackTrace();		}		//上传地址//		String url=URLConfigs.UploadHeadImage_ukey+myprefs.Ukey().get();		<span style="color:#ff0000;">String url="http://192.168.0.8/upload.php";</span>//		LogUtil.e(TAG, "upload img url :"+url);		AsyncHttpUtil.post_loading(context,url, params, new MyTextHttpResponseHandler() {			@Override			public void onSuccess(int status, Header[] arg1, String json) {				super.onSuccess(status, arg1, json);				LogUtil.e(TAG, "上传图片  json :"+json);				RespondBaseEntity entity=GsonUtil.GetFromJson(json, RespondBaseEntity.class);				if(entity.isStatus()){					//上传成功,设置图片					face.setImageBitmap(bmp);					ToastUtils.show(context, "上传成功");				}else{					ToastUtils.show(context, json);				}								myprefs.position().put(0);			}						@Override			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {				super.onFailure(arg0, arg1, arg2, arg3);				myprefs.position().put(0);//				arg3.printStackTrace();				ToastUtils.show(context, R.string.network_unavailable);			}
Copy after login

params.put("attach", uploadImg);  这里的attach参数是和服务端一一对应的,别乱改。。。。

String url="http://192.168.0.8/upload.php";   这个192.168.0.8是我的PHP部署的地址,改成你自己的就行了。


PS:别犯2,用了127.0.0.1    想想为啥不能用127.0.0.1

到此就是building,runing了。  发现OK。。。。   可以上传,并在www目录下找到upload目录,upload目录下有上传的图片。。。。




7.这就纳闷了。。。。 我又鼓起勇气找了PHP后端,跟他激烈的讨论一番后,发现是服务器坑了爹啊!  800块一年的服务器。。。。。唉。。。不说了。。。。



版权声明:本文为博主原创文章,未经博主允许不得转载。

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles