欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android将图片上传到php服务器的实例代码

程序员文章站 2022-07-11 23:29:22
layout中很普通,就是两个button和一个imageview

layout中很普通,就是两个button和一个imageview

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  >
  <button
    android:id="@+id/test"
    android:layout_width="368dp"
    android:layout_height="wrap_content"
    android:text="button1"
    android:textallcaps="false" />
  <button
    android:id="@+id/test2"
    android:layout_width="368dp"
    android:layout_height="wrap_content"
    android:text="button2"
    android:textallcaps="false"
    />
  <imageview
    android:id="@+id/image"
    android:layout_width="0dp"
    android:layout_height="495dp"
    />
</linearlayout>

在主页面中给按钮添加事件:

package success.xiaoyu.okhttp3;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.os.environment;
import android.os.handler;
import android.os.message;
import android.support.v7.app.appcompatactivity;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.widget.button;
import android.widget.imageview;
import java.io.file;
import java.io.ioexception;
import java.io.inputstream;
import java.util.concurrent.timeunit;
import okhttp3.call;
import okhttp3.callback;
import okhttp3.mediatype;
import okhttp3.multipartbody;
import okhttp3.okhttpclient;
import okhttp3.request;
import okhttp3.requestbody;
import okhttp3.response;
public class mainactivity extends appcompatactivity {
  private button button1,button2;
  private imageview imageview;
  private handler handler = new handler(){
    public void handlemessage(message msg) {
      bitmap bitmap = (bitmap)msg.obj;
      imageview.setimagebitmap(bitmap);
      //toast.maketext(mainactivity.this, environment.getexternalstoragedirectory()+"",toast.length_long).show();
    }
  };
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.layout);
    button1 = (button)findviewbyid(r.id.test);
    button2 = (button)findviewbyid(r.id.test2);
    imageview = (imageview)findviewbyid(r.id.image);
    button1.setonclicklistener(new view.onclicklistener() {//将服务器的图片读取到本地
      public void onclick(view view) {
        okhttpclient okhttpclient = new okhttpclient();
        request request = new request.builder()
                .url("http://115.159.217.226/xy.png")
                 .build();
        okhttpclient.newcall(request).enqueue(new callback() {
          public void onfailure(call call, ioexception e) {
          }
          public void onresponse(call call, response response) throws ioexception {
            inputstream inputstream = response.body().bytestream();
            bitmap bitmap = bitmapfactory.decodestream(inputstream);
            message msg = new message();
            msg.obj = bitmap;
            handler.sendmessage(msg);
          }
        });
      }
    });
    button2.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view view) {
        uploadmultifile();
      }
    });
  }
  private void uploadmultifile() {//将图片发送到服务器
    final string url = "http://115.159.217.226/upload.php";
    file file = new file( environment.getexternalstoragedirectory()+"/storage/emulated/0/", "xy.jpg");
    requestbody filebody = requestbody.create(mediatype.parse("application/octet-stream"), file);
    file file2 = new file( environment.getexternalstoragedirectory()+"/storage/emulated/0/", "yyw.jpg");
    requestbody filebody2 = requestbody.create(mediatype.parse("application/octet-stream"), file2);
    requestbody requestbody = new multipartbody.builder()
        .settype(multipartbody.form)
        .addformdatapart("image1", "xy.jpg", filebody)
        .addformdatapart("image2", "yyw.jpg", filebody2)
        .build();
    request request = new request.builder()
        .url(url)
        .post(requestbody)
        .build();
    final okhttp3.okhttpclient.builder httpbuilder = new okhttpclient.builder();
    okhttpclient okhttpclient = httpbuilder
        //设置超时
        .connecttimeout(10, timeunit.seconds)
        .writetimeout(15, timeunit.seconds)
        .build();
    okhttpclient.newcall(request).enqueue(new callback() {
      @override
      public void onfailure(call call, ioexception e) {
        log.e("aa", "uploadmultifile() e=" + e);
      }
      @override
      public void onresponse(call call, response response) throws ioexception {
        log.i("bb", "uploadmultifile() response=" + response.body().string());
      }
    });
  }
}

服务器端代码:

  <?php
   header('content-type: application/json;charset=utf-8');
if(empty($_files)) die('{"status":0,"msg":"错误提交"}');
$dirpath = './img/';//设置文件保存的目录
if(!is_dir($dirpath)){
  //目录不存在则创建目录
  @mkdir($dirpath);
}
$count = count($_files);//所有文件数
if($count<1) die('{"status":0,"msg":"错误提交"}');//没有提交的文件
$success = $failure = 0;
foreach($_files as $key => $value){
  //循环遍历数据
  $tmp = $value['name'];//获取上传文件名
  $tmpname = $value['tmp_name'];//临时文件路径
  //上传的文件会被保存到php临时目录,调用函数将文件复制到指定目录
  if(move_uploaded_file($tmpname,$dirpath.date('ymdhis').'_'.$tmp)){
    $success++;
  }else{
    $failure++;
  }
}
$arr['status'] = 1;
$arr['msg']   = '提交成功';
$arr['success'] = $success;
$arr['failure'] = $failure;
echo json_encode($arr);
  ?>

总结

以上所述是小编给大家介绍的android将图片上传到php服务器的实例代码,希望对大家有所帮助