Home > Backend Development > PHP Tutorial > Android upload pictures to server (PHP)

Android upload pictures to server (PHP)

WBOY
Release: 2016-07-28 08:30:04
Original
1918 people have browsed it

I want Android to implement a function of uploading pictures to the server. I didn’t know how to do it at first. What about server scripts and permission settings? When you think about writing Android, you still need to learn server things.

After studying for a few days, I finally completed this function and recorded it for easy review later.

Let’s talk about the server upload.php first

<?php
    $target_path  = "/var/www/upload/";//接收文件目录  
    $target_path = $target_path.($_FILES[&#39;file&#39;][&#39;name&#39;]);
    $target_path = iconv("UTF-8","gb2312", $target_path);
	echo exec(&#39;whoami&#39;) ;
    if(move_uploaded_file($_FILES[&#39;file&#39;][&#39;tmp_name&#39;], $target_path)) {  
       echo "The file ".( $_FILES[&#39;file&#39;][&#39;name&#39;])." has been uploaded.";
    }else{  
       echo " --There was an error uploading the file, please try again! Error Code: ".$_FILES[&#39;file&#39;][&#39;error&#39;];
    }
?>
Copy after login

Copy after login
$target_path  = "/var/www/upload/";//接收文件目录  
Copy after login
这里的文件位置一定要写完整,一开始我服务器的基站是 /var/www/下的 所以当初写的是
Copy after login
Copy after login
$target_path  = "/upload/";结果发现是不行的。所以这里是第一个注意点。如果读者想用这份脚本只需要把这个路径改成你们的目的<span style="font-family: Arial, Helvetica, sans-serif;">路径。</span>
Copy after login

The following is the Android MainActivty.java code

requires android-async-http-1.4.7.jar

package com.example.uploadbyasynchttp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class MainActivity extends Activity {

	
	private int userid = 1;
	private String username = "HelloWorld";
	@SuppressLint("SdCardPath") 
	private String filepath = "/mnt/sdcard/DCIM/Camera/IMG_20160612_103832.jpg";
	private String filepath1 = "/storage/emulated/0/DCIM/Camera/IMG_20160612_103832.jpg";
	private String uploadUrl = "http://120.55.67.135/test/upload.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button but_upload = (Button) findViewById(R.id.button_upload_id) ;
        
        but_upload.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				
				AsyncHttpClient client = new AsyncHttpClient();
		        RequestParams params = new RequestParams();
		        
		        //client.ENCODING_GZIP
		      
		        params.put("userid", userid);
		        params.put("username", username);
		      //添加文件
		        try {
		        	File f = new File(filepath1) ;
		        	if(f.exists()){
		        		Log.i("AsyncHttp", "Yes") ;
		        		params.put("file", f);
		        	}else{
		        		Log.i("AsyncHttp", "No") ;
		        	}
		        } catch (FileNotFoundException e) {
		            e.printStackTrace();
		        }
		         /*//////////////
		         * /把文件上传*/		        
		        client.post(uploadUrl, params, new AsyncHttpResponseHandler() {
		            @Override
		            public void onSuccess(int i, org.apache.http.Header[] headers, byte[] bytes) {
		                try {
		                    //获取返回内容
		                    String resp = new String(bytes, "utf-8");
		                     Log.i("AsyncHttp", resp) ;
		                    //在这里处理返回的内容,例如解析json什么的...
		                     
		                } catch (UnsupportedEncodingException e) {
		                    e.printStackTrace();
		                }
		            }
		            @Override
		            public void onFailure(int i, org.apache.http.Header[] headers, byte[] bytes, Throwable throwable) {
		                //在这里处理连接失败的处理...
		            }
		        });
			}
		}) ;
        
        
        
    }
    
}
Copy after login
想要使用上面的代码只需要该两处地方,第一:图片的路径位置 
Copy after login
 private String filepath = "/mnt/sdcard/DCIM/Camera/IMG_20160612_103832.jpg";
Copy after login
 Android 上传图片到服务器(PHP)
第二:你服务器放upload脚本文件 
Copy after login
 private String uploadUrl = "http://120.55.67.135/test/upload.php";
Copy after login
下面是我的路径位置。(因为/var/www/是基地/使用只需要写/test/upload.php和上面upload.php路径是不一样)
Copy after login
Copy after login

xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:c >

    <Button
        android:id="@+id/button_upload_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击上传" />

</RelativeLayout>
Copy after login
注意权限:<uses-permission android:name="android.permission.INTERNET" />
Copy after login

The above is all the code, but you will find that there is still no image generated. I checked the information because of permission issues.

The destination directory where we store the images does not have permissions for the user who executes PHP. The user who executes the PHP script is not the same user who wrote the script code and created the image folder. You also need to

  1. modify the user who owns the fixed storage folder of the pictures and change it to the user who runs apache to execute the PHP script.
  2. Change the permissions of the folder to 755

So who is the user running apache? We use the PHP script to get:

<code>echo exec('whoami'); //获得执行该文件的用户名,从而修改图片文件夹的权限</code>
Copy after login

In this way, I got the user who executed the script: www-data. You get a lot Maybe it's different from mine.
Let’s modify the user who owns the folder:

<code>chown www-data -R  /var/www//upload/</code>
Copy after login
<code>/var/www//upload/</code><span>是我存放图片的目标路径,-R代表递归的给这个目录下的文件夹修改所属用户。</span>
Copy after login

Then modify the folder permissions

<code>chmod 775 -R  </code><span>/var/www/upload/</span>
Copy after login

That’s it. Click the upload button, refresh your upload folder, and you can see the picture.

Refer to the following three blogs.

http://www.th7.cn/Program/php/201510/593494.shtml

http://www.cnblogs.com/bruce27/p/5361161.html

http://blog.csdn.net/fancylovejava/article/details/13506745

The above introduces Android uploading pictures to the server (PHP), including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template