Android OkHttp3 上传多张图片

经过实践,android与php交互,已经成功搞定!

一、Android 端

 /**
     * 上传文件及参数
     */
    private void sendMultipart(){
        File sdcache = getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024;
        //设置超时时间及缓存
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));


        OkHttpClient mOkHttpClient=builder.build();

        MultipartBody.Builder mbody=new MultipartBody.Builder().setType(MultipartBody.FORM);

        List fileList=new ArrayList();
        File img1=new File("/sdcard/wangshu.jpg");
        fileList.add(img1);
        File img2=new File("/sdcard/123.jpg");
        fileList.add(img2);
        int i=0;
        for(File file:fileList){
            if(file.exists()){
                Log.i("imageName:",file.getName());//经过测试,此处的名称不能相同,如果相同,只能保存最后一个图片,不知道那些同名的大神是怎么成功保存图片的。
                mbody.addFormDataPart("image"+i,file.getName(),RequestBody.create(MEDIA_TYPE_PNG,file));
                i++;
            }
        }

        RequestBody requestBody =mbody.build();
        Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + "...")
            .url("http://192.168.1.105/interface/index.php?action=sendMultipart")
            .post(requestBody)
            .build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("InfoMSG", response.body().string());
            }
        });
    }





二、Php服务端

if ($act == "sendMultipart") {
	$result="";
	try {
		foreach ($_FILES as $key => $val) {
			$imgName = time().rand(1000, 9999);//随机数
			$folder = "images";//接口文件同目录下创建此文件夹,当然也可以通过代码的形式判断/创建
			$file_dir = $folder . "/" . $imgName . ".jpg";
			if (move_uploaded_file($val["tmp_name"], $file_dir)) {
				$result .= $val["name"] . "保存成功";
			} else {
				$result .= "在服务器中保存失败" . $val["tmp_name"] . "--------";
			}
			echo "返回信息:" . $result."
\n"; } } catch(exception $ex) { echo $ex; } }


没什么可总结的了,都在注释里了。









你可能感兴趣的:(Android,Studio)