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

 更新时间:2017年07月28日 09:44:41   作者:潇遥快乐  
这篇文章主要介绍了Android将图片上传到php服务器的实例代码,需要的朋友可以参考下

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服务器的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

最新评论