okhttp 上传图片 PHP服务端接收

Android:

 OkHttpClient mOkHttpClent = new OkHttpClient();
  System.out.println(path);
  File file = new File(path);
  MultipartBody.Builder builder = new MultipartBody.Builder()
          .setType(MultipartBody.FORM)
          .addFormDataPart("img", file.getName(),
                  okhttp3.RequestBody.create(  MediaType.parse("image/png"), file));

  okhttp3.RequestBody requestBody = builder.build();
  Request request = new Request.Builder()
          .url(url+"upload")
          .post(requestBody)
          .build();
  Call call = mOkHttpClent.newCall(request);
  call.enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
          Log.e(TAG, "onFailure: "+e );
          runOnUiThread(new Runnable() {
              @Override
              public void run() {
                  Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
              }
          });
      }
      @Override
      public void onResponse(Call call, Response response) throws IOException {
          Log.e(TAG, "成功"+response);
          runOnUiThread(new Runnable() {
              @Override
              public void run() {
                  Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();
              }
          });
      }
  }
);

 

php:

 

public function upLoad(Request $request)

{

    header('Content-type:application/json;charset=utf-8');

    if (empty($_FILES)) {

        $code = 0;

        $msg = '无上传文件!';

    } else {

        $dirPath = './img/';//设置文件保存的目录

        if (!is_dir($dirPath)) {

            //目录不存在则创建目录

            @mkdir($dirPath);

        }

        $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++;

            }

        }

        $code = 1;

        $msg = '提交成功';

    }

    $result = '{"status":'.$code.',"msg":"'. $msg . '"}';

    return $result;

}

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(PHP)