Android OkHttp 结合php 多图片上传实例
时间:2021-08-04 08:33:05|栏目:Android代码|点击: 次
今天写项目的时候需要多图片上传,就用okhttp简单写一个例子。
public class MainActivity extends AppCompatActivity { private OkHttpClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); client = new OkHttpClient(); postImage(); } private void postImage(){ //这里方便演示。读取drawable里的图片。 Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.demo); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream); MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM) .addFormDataPart("img_1","1.jpg", RequestBody.create(MediaType.parse("image/jpeg"),byteArrayOutputStream.toByteArray())) .addFormDataPart("img_2","2.jpg", RequestBody.create(MediaType.parse("image/jpeg"),byteArrayOutputStream.toByteArray())) ; //有多个图片就用for循环添加即可 MultipartBody build = builder.build(); okhttp3.Request bi = new okhttp3.Request.Builder() .url("后台地址") .post(build) .build(); client.newCall(bi).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.i("TAG", "onFailure: 失败"); } @Override public void onResponse(Call call, okhttp3.Response response) throws IOException { Log.i("TAG", "onResponse: " + response.body().string()); //提交成功处理结果.... } }); } }
配合PHP后台接收图片地址:
具体代码如下,支持多个图片的上传,返回json格式,方便客户端进行处理数据。
<?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端使用okHttp上传,测试上传图如下: