Android上传图片到PHP服务器并且支持浏览器上传文件(word、图片、音乐等)

暑假已经过了一半了,这才完成计划当中的第二个任务。虽然进度是慢了点。但也算是暑假的收获吧。下面我就把我学习当中的收获记录在此。

还是跟以往一样,先上图片。

操作的步骤:打开程序----》选择上传的照片-----》点击返回键------》显示没有选择上传图片的toast------》点击上传的图片-----》打印图片的存储的物理路径----》询问是否确认上传选择的图片-----》确认则显示上传成功----》取消则退出

php代码:

<?php
//上传文件进行简单错误过滤
if($_FILES['userfile']['error']>0){
    exit('上传文件有错误');
    }
    //定义存放文件的真实路径(需要手动创建)
    $path = "D:/xampp/htdocs/xampp/upload/";
    //定义存放上传文件的真实路径名
    $name = $_FILES['userfile']['name'];
    
    //将文件的名字的字符编码从utf-8转换成gb2312
    $name = iconv ("UTF-8","GB2312",$name);
    //将上传文件移动到指定目录文件中
    $path = $path.$name;
    if(move_uploaded_file($_FILES['userfile']['tmp_name'],$path)){
        echo "文件上传成功!";
        // print_r($_FILES);

        }else{
        echo "文件上传失败!";
       $_FILES['userfile']['tmp_name'] ;
        print_r($_FILES);

            }
?>

android代码:

MainActivity.java

package com.itcast.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Button btn_select;
    private static final int FLAGE_LOAD_IMAGE = 1;
    public static String pathName;
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FLAGE_LOAD_IMAGE) {
            if (data == null) {
                Toast.makeText(this, "你没有选择任何图片", 1).show();
            }else{
                Uri uri = data.getData();
                if (uri == null) {
                    Toast.makeText(this, "你没有选择任何图片", 1).show();
                }else{
                    String path = null;
                    String[] pojo = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(uri, pojo, null, null, null);
                    if (cursor != null) {
                        int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
                        cursor.moveToFirst();
                        path = cursor.getString(columnIndex);
                        cursor.close();
                    }
                    if (path != null) {
                        Toast.makeText(this, "图片的物理路径"+ path, 0).show();
                        pathName = path;
                        new AlertDialog.Builder(this).setTitle("提示")
                            .setMessage("你要上传选择的图片吗?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    doUpload();
                                    
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    
                                }
                            }).create().show();
                    }else{
                        Toast.makeText(this, "未能获得图片的物理路径", 0).show();
                    }
                }
            }
        }
    }
    private void doUpload(){
        new Thread(new Runnable(){
            public void run(){
                try{
                    //文件二进制数据
                    InputStream in = new FileInputStream(new File(pathName));
                    //普通字符串数据
                    Map<String,String> data = new HashMap<String,String>();
                    final String result = userService.userUpload(in, data);
                    runOnUiThread(new Runnable(){
                        public void run(){
                            Toast.makeText(MainActivity.this, result, 1).show();
                        }
                    });
                    
                    
                }catch(Exception e){
                    e.printStackTrace();
                    runOnUiThread(new Runnable(){
                        public void run(){
                            Toast.makeText(MainActivity.this, "上传错误", 1).show();
                            }
                    });
                }
            }
        }).start();
    }
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.btn_select = (Button) this.findViewById(R.id.btn_select);
        this.btn_select.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, FLAGE_LOAD_IMAGE);
            }
        });
    }

   
    
}

UserService.java 一个接口代码为:

package com.itcast.upload;

import java.io.InputStream;
import java.util.Map;

public interface UserService {
    public String userUpload(InputStream in,Map<String,String> data)throws Exception;
}

UserServiceImpl.java 实现UserService接口

代码为:

package com.itcast.upload;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

 class UserServiceImpl implements UserService {

    @Override
    public String userUpload(InputStream in, Map<String, String> data)
            throws Exception {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://192.168.1.103/xampp/upData.php");
        //要把数据封装到post里面去
        /*Httpmine*/
        MultipartEntity entity = new MultipartEntity();
        //二进制的流文件数据对象
        entity.addPart("userfile",new InputStreamBody(in, "multipart/form-data",MainActivity.pathName));
        //数据放到post
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            
        }
        String result = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
        return result;
    }

}

需要添加的权限有:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>

至此,android端的代码书写完毕。

下面是浏览器端的代码:

upload.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
//通过页面加载事件实现上传文件时显示进度条
function sub(){
    //实现Ajax对象
    var obj = new XMLHttpRequest();
    //接收响应的信息
    obj.onreadystatechange = function(){
        if(obj.readyState == 4 && obj.status == 200){
            document.getElementById('con').innerHTML = obj.responseText;
        }
        }
        //onprogress 属性通过主浏览器的“事件对象evt”感知当前附件上传情况
        obj.upload.onprogress = function(evt){
            //上传附件大小的百分比
            //其中evt.total 表示附件的总大小 evt.loaded表示已经上传附件大小
            var per = Math.floor((evt.loaded/evt.total)*100)+"%";
            //当前上传文件时,显示进度条
            document.getElementById('parent').style.display = 'block';
            //通过上传百分比设置进度条样式的宽度
            document.getElementById('son').style.width = per;
            //在进度条上显示上传的进度值
            document.getElementById('son').innerHTML = per;
            }
        //通过FormData 收集零散的上传文件信息
        var fm = document.getElementById("userfile3").files[0];
        var fd = new FormData();
        fd.append('userfile',fm);
    
        obj.open('post','upData.php');
        obj.send(fd);
        }
</script>
<style type="text/css">
#parent {
    width:200px;
    height:20px;
    border:2px solid gray;
    background:lightgray;
    display:none;
    }
    #son{
        width:0;
        height:100%;
        background:lightgreen;
        text-align:center;
        }
</style>
</head>

<body>
    <h2> Ajax实现进度条上传文件</h2>
    <div id="parent">
    <div id="son"></div>    
    </div>
    <p id="con"></p>
    <input type="file" name="userfile" id="userfile3"  />
    <br /><br />
    <input type="button" onclick="sub()" value="文件上传"/>
</body>
</html>

 遇到的问题:

解决的办法是修改android端的代码:

 

解决的办法是:

posted on 2016-08-04 23:39  kang_ya_ping  阅读(574)  评论(0编辑  收藏  举报

导航