Use OKHttp to upload pictures---b509 Tips

Recently, the project needs to upload pictures. I recommend a framework okHttp to everyone. It is very useful. As for the download method, you can Baidu by yourself. The function of uploading pictures, not much nonsense,,,

The first step, github downloads the jar package of okhttp (not much to say here, Baidu)

The second part, new construction. . . . (10,000 words omitted) The
simple layout is as follows

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:fitsSystemWindows="true"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.lockscreen.activity.UploadActivity">


    <Button
        android:text="从相册选择照片"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:id="@+id/button_get_photo"
        android:layout_margin="10dp"/>

    <Button
        android:text="上传"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:id="@+id/btn_upload_img"
        android:layout_margin="10dp"/>


    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="200dp"
        android:minWidth="200dp"
        android:layout_gravity="center"
        android:id="@+id/imageView_camera"/>
</LinearLayout>

The third step, the implementation of the corresponding java code (I mainly use Okhttp3 here):

package com.lockscreen.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.lockscreen.R;

import java.io.File;
import java.io.IOException;

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 UploadActivity extends Activity implements View.OnClickListener {

    private Button btn_upload_img, mButtonGetPhoto;
    private ImageView mImageViewPhoto;
    //处理手机图片
    public static final int PHOTO_RESOUL = 3;
    public static final String IMAGE_UNSPECIFIED = "image/*";
    private Uri uri;
    //okhttp 上传图片
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        initUI();
    }

    //初始化UI
    private void initUI() {
        mButtonGetPhoto = (Button) findViewById(R.id.button_get_photo);
        btn_upload_img = (Button) findViewById(R.id.btn_upload_img);
        mImageViewPhoto = (ImageView) findViewById(R.id.imageView_camera);
        mButtonGetPhoto.setOnClickListener(this);
        btn_upload_img.setOnClickListener(this);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_upload_img:
                uploadImg();
                break;
            case R.id.button_get_photo:
                //获取本地相册
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                startActivityForResult(intent, PHOTO_RESOUL);
                Log.e("gaoyu", "调用相册成功");
                break;

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //处理结果
        if (requestCode == PHOTO_RESOUL) {
            uri = data.getData();
            if (uri != null) {
                mImageViewPhoto.setImageURI(uri);
                Log.e("gaoyu", "照片显示成功");
            }
        }
    }


    /**
     * 上传方法
     */
    private void uploadImg() {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File f = new File(String.valueOf(uri));
        if (f != null) {
            builder.addFormDataPart("img", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
        }

        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url("这里放服务器地址")//地址
                .post(requestBody)//添加请求体
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(UploadActivity.this, "上传失败:e.getLocalizedMessage() = ", Toast.LENGTH_SHORT).show();
                Log.e("gaoyu", "上传失败:e.getLocalizedMessage() = "+e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Toast.makeText(UploadActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                Log.e("gaoyu", "上传照片成功:response = "+ response.body().string());
            }
        });
    }
}

Everything that the basic client needs is here. If you need the implementation of the server, you can pay
attention to it. The comments in the code are very clear. . . thankyou! ———b509 Tips

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325476406&siteId=291194637