1.OkHttp头像上传

  1. 头像上传实体类
    /**
    * code : 200
    * res : 上传文件成功
    * data : {"url":"http://yun918.cn/study/public/uploadfiles/img/image1.png"}
    */
     private int code;
     private String res;
     private DataBean data;
 
     public int getCode() {
         return code;
     }
 
     public void setCode(int code) {
         this.code = code;
     }
 
     public String getRes() {
         return res;
     }
 
     public void setRes(String res) {
         this.res = res;
     }
 
     public DataBean getData() {
         return data;
     }
 
     public void setData(DataBean data) {
         this.data = data;
     }
 
     public static class DataBean {
         /**
          * url : http://yun918.cn/study/public/uploadfiles/img/image1.png
          */
 
         private String url;
 
         public String getUrl() {
             return url;
         }
 
         public void setUrl(String url) {
             this.url = url;
         }
     }

2.上传头像工具类
//sd卡是否存在
public static boolean sdCardIsAvailable() {
if(Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
}
//获取sd卡路径
public static String getSDPath() {
File sdDir = null;
if (sdCardIsAvailable()) {
//获取根目录
sdDir = Environment.getExternalStorageDirectory();
}
return sdDir.toString();
}

     //byte[]转bitmap
     public static Bitmap getBitmapByBytes(byte[] bytes, BitmapFactory.Options options) {
         if (bytes != null) {
             if (options != null) {
                 return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
             } else {
                 return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
             }
         }
         return null;
     }
 
     //Bitmap转byte[]
     public static byte[] getByteByBmp(Bitmap bmp) {
         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
         bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
         return outputStream.toByteArray();
     }

3.文件上传MainActivity布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.a19950115.kaoshi.MainActivity">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#28A5DF"
    android:minHeight="?android:actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="主页"
        android:textColor="#ffffff"
        android:textSize="20sp" />
</android.support.v7.widget.Toolbar>

<com.jcodecraeer.xrecyclerview.XRecyclerView
    android:id="@+id/xrlv"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

4.头像上传布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.a19950115.kaoshi.TuPian.Activity_TouXiang">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#28A5DF"
    android:minHeight="?android:actionBarSize"

android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="图片上传"
        android:textColor="#ffffff"
        android:textSize="20sp" />
</android.support.v7.widget.Toolbar>

<ImageView
    android:id="@+id/img"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="10dp"
    android:src="@mipmap/ic_launcher" />

<TextView
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp" />

<TextView
    android:id="@+id/tv1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp" />

<Button
    android:id="@+id/login"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="图片上传" />

</LinearLayout>

5.头像上传MainActivity步骤
public class Activity_TouXiang extends AppCompatActivity implements View.OnClickListener {
private Toolbar toolBar;
private ImageView img;
private TextView tv;
private TextView tv1;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__tou_xiang);
initView();
}

private void initView() {
    //获取Toolbar控件
    toolBar = (Toolbar) findViewById(R.id.toolBar);
    toolBar.setTitle("");
    setSupportActionBar(toolBar);
    toolBar.setNavigationIcon(R.drawable.aa);
    toolBar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
      //获取控件
    img = (ImageView) findViewById(R.id.img);
    tv = (TextView) findViewById(R.id.tv);
    tv1 = (TextView) findViewById(R.id.tv1);
    login = (Button) findViewById(R.id.login);
    //原始图片地址
    tv.setText(Utils.getSDPath() + "/r.jpg");
    //加载一张圆形图片
    RequestOptions options = RequestOptions.circleCropTransform()
            .placeholder(R.mipmap.ic_launcher)
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
            .skipMemoryCache(true);
    Glide.with(this).load(R.drawable.f).apply(options).into(img);
     //按钮点击事件监听
    login.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.login:
            uploadImage();
            break;
    }
}

//文件上传
private void uploadImage() {
    File file = new File(Utils.getSDPath() + "/r.jpg");
    if (file.exists()) {
        //上传文件的格式
        String format = "image/jpg";   //image/jpg  image/gif multipart/form-data
        RequestBody requestBody = RequestBody.create(MediaType.parse(format), file);
        //设置上传文件的内容
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("key", "image110")  //传参数
                .addFormDataPart("file", file.getName(), requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .build();
        //设置上传地址和内容
        Request request1 = new Request.Builder()
                .url("http://yun918.cn/study/public/file_upload.php")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request1);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("onFailure", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Gson gson = new Gson();
                final ImageBean imageBean = gson.fromJson(result, ImageBean.class);
                if (imageBean.getCode() == 200) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateImageView(imageBean);
                        }
                    });
                }
                Log.i("result", result);
            }
        });
    }
}

//更新本地imageview图片
private void updateImageView(ImageBean imageBean) {
    tv1.setText(imageBean.getData().getUrl());
    RequestOptions options = new RequestOptions().circleCrop();

Glide.with(this).load(imageBean.getData().getUrl()).apply(options).into(img);
}
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,738评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,377评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,774评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,032评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,015评论 5 361
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,239评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,724评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,374评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,508评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,410评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,457评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,132评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,733评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,804评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,022评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,515评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,116评论 2 341

推荐阅读更多精彩内容