android使用PHP上传图片到服务器

PHP端代码

<?php

    $response=array();

//    $target = "./upload/";//

    $target_path =basename($_FILES['uploadedfile']['name']);
//    $another_path = $target . basename($_FILES['anotherfile']['name']);

    if  (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
    {
        $response['response']="The file ".basename($_FILES['uploadedfile']['name'])." has been uploaded";
        echo json_encode($response);
    }
    else
    {
        $response['response']="There was an error uploading the file, please try again!Here is the wrong info: ".$_FILES['uploadedfile']['error'];
        echo json_encode($response);
    }

FILES[uploadedfile][name][]android[][name] target_path 表示的是图片上传放在哪个位置,如果是以本机做服务器,那么图片默认会被保存在\xampp\htdocs路径下,如果想更改成其他路径,必须保证那个路径已存在,否则会报错。
move_uploaded_file( FILES[uploadedfile][tmpname], target_path)是用来对图片进行移动的操作,第一个参数表示移动的文件,第二个参数表示移动的路径。如果移动成功返回Ture,否则返回False。
最后根据是否成功将文件上传,返回json数据给android客户端,记得返回的数据一定要是一个带标示的数组(如这里的$response[‘response’]中的‘response’),因为在android端接受这些数据的时候要通过这个标示来取出数据。

接下来是安卓端代码:

public class UploadConnect extends AsyncTask<String,Integer,String> {
    private ProgressDialog progress;
    private Context mContext;


    public UploadConnect(ProgressDialog progressDialog,Context context){
        progress=progressDialog;
        mContext=context;
    }


    @Override
    protected void onPreExecute(){
        progress=ProgressDialog.show(mContext,"上传中~","请稍后~",true,false);

    }

    //----------------------doInBackground----开始执行----------------------
    @Override
    protected String doInBackground(String... params) {
        String uploadUrl=params[0];
        String srcPath=params[1];
        String srcPath2 = Environment.getExternalStorageDirectory().getPath()+"/1.jpg";

        HttpClient httpclient = new DefaultHttpClient();

        //--------------设置连接参数···具体怎么用不清楚···
        httpclient.getParams().setParameter(
                CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(uploadUrl);

        //-------------使用MultipartEntity-----
        MultipartEntity entity = new MultipartEntity();

        //在表单中,增加第一个input type='file'元素,name=‘uploadedfile’
        File file = new File(srcPath);

        //-----------------使用filebody封装-----------
        FileBody fileBody = new FileBody(file);
        entity.addPart("uploadedfile", fileBody);

//        //在表单中,增加第一个input type='file'元素,name=‘anotherfile’
//        File file2 = new File(srcPath2);
//        FileBody fileBody2 = new FileBody(file2);
//        entity.addPart("anotherfile", fileBody2);

        httppost.setEntity(entity);
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
            Log.d("msg","httpclient has been execute!");

        } catch (IOException e) {
            e.printStackTrace();
            Log.d("msg"," "+e.toString()+"       lehgth 66 has wrong! "+e.getMessage());
        }

        HttpEntity responseEntity = response.getEntity();
        Log.d("msg","get the response entity:"+responseEntity);


        String returnResult= null;
        try {
            returnResult = EntityUtils.toString(responseEntity, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("msg", " " + e.toString());
        }
        Log.d("msg","returnResult is"+returnResult);

        String state=parseLoginJSON(returnResult);

        Log.d("msg","state is"+state);


        httpclient.getConnectionManager().shutdown();

        return state;
    }


//    //--------------------------------------onProgressUpload-------------------------
//
//    @Override
//    protected void onProgressUpdate(Integer... values ){
//        int value=values[0];
//        progress.setProgress(value);
//    }


    //----------------------------------onPostExecute----------------------

    @Override
    protected void onPostExecute(String result){
        progress.dismiss();
        Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
        Log.d("msg", "   " + result);
    }



    //解析JSON格式
    public static String parseLoginJSON(String result) {
        try {
            String message=new String();
            message="";
            Log.d("msg", "进入解析数据");

            //判断返回的值是JsonArray还是JsonObject(前者含有“[”“]”字符)
            int signal =result.indexOf("[");
            //没有找到相关字符的话,返回-1

            //!=-1,说明有字符,是JsonArray
            if(signal!=-1) {
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Log.d("msg", "创建JSONArray对象成功" + jsonObject);

//                int id=jsonObject.getInt("id");
//            int state = jsonObject.getInt("state");
                    message = message + jsonObject.getString("response");
                }
            }
            //不含“[”,说明是JsonObject
            else{
                Log.d("msg","不含“[”");
                JSONObject jsonObject = new JSONObject(result);

//                int id=jsonObject.getInt("id");
                message = jsonObject.getString("response");
            }
            Log.d("msg"," message" + message);

            return message;

        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("msg", "WRONG "+e.toString()+"在第156行");
        }

        Log.d("msg", "要返回something wrong了");

        return "something wrong";
    }
}

这里代码没有进行整理,将就着看吧。
其中在parseLoginJSON()函数中使用了 int signal =result.indexOf(“[“);
判断返回的json数据是jsonArray还是jsonObject(前者会用[ ]将所有jsonObject括起来,后者只有{ }这样一个花括号 )
这里与android去验证登陆用户名和密码最大的不同就是使用了这些代码:

        //--------------设置连接参数···具体怎么用不清楚···
        httpclient.getParams().setParameter(
                CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(uploadUrl);

        //-------------使用MultipartEntity-----
        MultipartEntity entity = new MultipartEntity();

        //在表单中,增加第一个input type='file'元素,name=‘uploadedfile’
        File file = new File(srcPath);

        //-----------------使用filebody封装-----------
        FileBody fileBody = new FileBody(file);
        entity.addPart("uploadedfile", fileBody);

这段代码暂时还不知道为什么要这么用·····················

源码来自于http://blog.csdn.net/harvic880925/article/details/17565481,自己修改了一些

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值