当前位置:   article > 正文

【手把手教】Android开发两种方式实现图片的上传下载_android 上传图片

android 上传图片

Android 图片上传的应用场景

Android开发中,很多时候我们需要进行图片,文件的上传下载,最直接的一个应用场景就是用户头像的保存与切换,以及像即时通讯中的图片发送等任何在App中设计图片的应用都是通过图片的上传下载完成的。

Android 如何实现图片的上传下载?

近期在工作中遇到了需要实现其图片上传的功能,特此写了一个demo帮助更多的人进行相关学习

这是demo的效果图:

其实整个过程也非常简单,图片上传可以整理为访问本地选取图片,以及图片提交上传(后端提供上传图片接口,这里只对安卓技术进行相关说明)。

实现这一过程这边使用了PictureSelector+Xutill或者PictureSelector+OkHttp进行了功能的实现。

pictureSelector是一个强大的Android选取图片,上传图片的开源工具,支持从相册或拍照选择图片或视频、音频,支持动态权限获取、裁剪(单图or多图裁剪)、压缩、主题自定义配置等功能、适配android 6.0+系统,而且你能遇到的问题,README文档都有解决方案。

xutils是前几年比较火得一个开源框架,主要分四个重要的模块:ViewUtils,HttpUtils,BitmapUtils,DbUtils,包含了很多实用的工具类,支持大文件上传,且有更全面的http请求协议支持,拥有灵活的Orm,支持事件注解且不受代码混淆影响。

xUtils3网络模块大大方便了在实际开发中网络模块的开发,xUtils3网络模块大致包括GET请求、POST请求、请求方式、上传文件、下载文件、使用缓存等功能

Android 图片上传下载实现过程(小白教学)

Demo的UI界面:MainActivity的activity_main xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:background="@color/coreGray"
  8. android:orientation="vertical"
  9. tools:context=".MainActivity">
  10. <include layout="@layout/layout_title"/>
  11. <LinearLayout
  12. style="@style/LoginLayoutStyle"
  13. android:layout_width="match_parent">
  14. <TextView
  15. android:id="@+id/aaa"
  16. android:layout_width="wrap_content"
  17. android:layout_height="wrap_content"
  18. android:layout_gravity="center"
  19. android:text="AAA:"
  20. android:textColor="@color/black60"
  21. android:textSize="20dp" />
  22. <com.tz.picturedemo.view.ClearEditText
  23. android:id="@+id/qs_username2"
  24. style="@style/EditTextStyle"
  25. android:layout_width="match_parent"
  26. android:layout_height="wrap_content"
  27. android:hint="请输入AAAA"
  28. android:inputType="text"
  29. android:lines="1"
  30. android:singleLine="true"
  31. android:textCursorDrawable="@null"
  32. app:regexType="name" />
  33. </LinearLayout>
  34. <LinearLayout
  35. style="@style/LoginLayoutStyle"
  36. android:layout_width="match_parent">
  37. <TextView
  38. android:layout_width="wrap_content"
  39. android:layout_height="wrap_content"
  40. android:layout_gravity="center"
  41. android:text="BBB:"
  42. android:textColor="@color/black60"
  43. android:textSize="20dp" />
  44. <com.tz.picturedemo.view.ClearEditText
  45. android:id="@+id/qs_username3"
  46. style="@style/EditTextStyle"
  47. android:layout_width="match_parent"
  48. android:layout_height="wrap_content"
  49. android:hint="请输入BBBB"
  50. android:inputType="text"
  51. android:lines="1"
  52. android:singleLine="true"
  53. android:textCursorDrawable="@null"
  54. app:regexType="name" />
  55. </LinearLayout>
  56. <LinearLayout
  57. style="@style/LoginLayoutStyle"
  58. android:layout_width="match_parent">
  59. <TextView
  60. android:layout_width="wrap_content"
  61. android:layout_height="wrap_content"
  62. android:layout_gravity="center"
  63. android:text="CCC:"
  64. android:textColor="@color/black60"
  65. android:textSize="20dp" />
  66. <com.tz.picturedemo.view.ClearEditText
  67. android:id="@+id/qs_username"
  68. style="@style/EditTextStyle"
  69. android:layout_width="match_parent"
  70. android:layout_height="wrap_content"
  71. android:hint="请输入CCCC"
  72. android:inputType="text"
  73. android:lines="1"
  74. android:singleLine="true"
  75. android:textCursorDrawable="@null"
  76. app:regexType="name" />
  77. </LinearLayout>
  78. <TextView
  79. android:layout_width="match_parent"
  80. android:layout_height="wrap_content"
  81. android:text="上传图片"
  82. android:textColor="@color/black60"
  83. android:padding="10dp"
  84. android:textSize="20sp"/>
  85. <LinearLayout
  86. android:layout_width="match_parent"
  87. android:layout_height="wrap_content"
  88. android:paddingTop="20dp"
  89. android:orientation="horizontal">
  90. <LinearLayout
  91. android:layout_width="wrap_content"
  92. android:layout_height="wrap_content"
  93. android:layout_weight="1"
  94. android:layout_gravity="center"
  95. android:gravity="center"
  96. android:orientation="vertical">
  97. <ImageView
  98. android:id="@+id/picture1"
  99. android:layout_width="wrap_content"
  100. android:layout_height="wrap_content"
  101. android:src="@mipmap/ic_add_image"/>
  102. <TextView
  103. android:layout_width="wrap_content"
  104. android:layout_height="wrap_content"
  105. android:paddingTop="10dp"
  106. android:text="正面"
  107. android:textColor="@color/black60"
  108. android:textSize="18sp" />
  109. </LinearLayout>
  110. <LinearLayout
  111. android:layout_width="wrap_content"
  112. android:layout_height="wrap_content"
  113. android:layout_weight="1"
  114. android:layout_gravity="center"
  115. android:gravity="center"
  116. android:orientation="vertical">
  117. <ImageView
  118. android:id="@+id/picture2"
  119. android:layout_width="wrap_content"
  120. android:layout_height="wrap_content"
  121. android:src="@mipmap/ic_add_image"/>
  122. <TextView
  123. android:layout_width="wrap_content"
  124. android:layout_height="wrap_content"
  125. android:paddingTop="10dp"
  126. android:text="侧面"
  127. android:textColor="@color/black60"
  128. android:textSize="18sp" />
  129. </LinearLayout>
  130. <LinearLayout
  131. android:layout_width="wrap_content"
  132. android:layout_height="wrap_content"
  133. android:layout_weight="1"
  134. android:layout_gravity="center"
  135. android:gravity="center"
  136. android:orientation="vertical">
  137. <ImageView
  138. android:id="@+id/picture3"
  139. android:layout_width="wrap_content"
  140. android:layout_height="wrap_content"
  141. android:src="@mipmap/ic_add_image"/>
  142. <TextView
  143. android:layout_width="wrap_content"
  144. android:layout_height="wrap_content"
  145. android:paddingTop="10dp"
  146. android:text="反面"
  147. android:textColor="@color/black60"
  148. android:textSize="18sp" />
  149. </LinearLayout>
  150. </LinearLayout>
  151. <Button
  152. android:id="@+id/makesure"
  153. android:layout_width="match_parent"
  154. android:layout_height="45dp"
  155. android:text="提交"
  156. android:layout_marginLeft="15dp"
  157. android:layout_marginRight="15dp"
  158. android:layout_marginTop="50dp"
  159. android:textSize="20dp"
  160. android:textColor="@color/white"
  161. android:background="@drawable/share_item_blue_bg"
  162. />
  163. </LinearLayout>

我在此处为了界面美化,引用了一些第三方自定义view大家可自行替换成原生即可

Demo功能核心代码 MainActivity

  1. package com.tz.picturedemo;
  2. import static com.luck.picture.lib.config.SelectMimeType.ofImage;
  3. import androidx.appcompat.app.AppCompatActivity;
  4. import android.graphics.Color;
  5. import android.os.Bundle;
  6. import android.util.Log;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.ImageView;
  10. import android.widget.Toast;
  11. import com.alibaba.fastjson.JSON;
  12. import com.bumptech.glide.Glide;
  13. import com.luck.picture.lib.basic.PictureSelector;
  14. import com.luck.picture.lib.config.PictureConfig;
  15. import com.luck.picture.lib.config.SelectMimeType;
  16. import com.luck.picture.lib.entity.LocalMedia;
  17. import com.luck.picture.lib.interfaces.OnResultCallbackListener;
  18. import org.xutils.common.Callback;
  19. import org.xutils.http.RequestParams;
  20. import org.xutils.x;
  21. import java.io.File;
  22. import java.io.IOException;
  23. import java.util.ArrayList;
  24. import java.util.List;
  25. import okhttp3.Call;
  26. import okhttp3.MediaType;
  27. import okhttp3.MultipartBody;
  28. import okhttp3.OkHttpClient;
  29. import okhttp3.Request;
  30. import okhttp3.RequestBody;
  31. import okhttp3.Response;
  32. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  33. private ImageView mPicture1;
  34. private ImageView mPicture2;
  35. private ImageView mPicture3;
  36. private List<String> PictureArr=new ArrayList<>();
  37. private Button mBtn;
  38. @Override
  39. protected void onCreate(Bundle savedInstanceState) {
  40. super.onCreate(savedInstanceState);
  41. setContentView(R.layout.activity_main);
  42. getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN );//这句让view 顶到顶
  43. getWindow().setStatusBarColor(Color.TRANSPARENT);//这句让状态栏透明
  44. initVew();
  45. }
  46. private void initVew() {
  47. mPicture1=findViewById(R.id.picture1);
  48. mPicture2=findViewById(R.id.picture2);
  49. mPicture3=findViewById(R.id.picture3);
  50. mBtn=findViewById(R.id.makesure);
  51. mPicture1.setOnClickListener(this);
  52. mPicture2.setOnClickListener(this);
  53. mPicture3.setOnClickListener(this);
  54. mBtn.setOnClickListener(this);
  55. }
  56. @Override
  57. public void onClick(View view) {
  58. switch (view.getId()) {
  59. case R.id.picture1:
  60. photoAndAll(mPicture1);
  61. break;
  62. case R.id.picture2:
  63. photoAndAll(mPicture2);
  64. break;
  65. case R.id.picture3:
  66. photoAndAll(mPicture3);
  67. break;
  68. case R.id.makesure:
  69. break;
  70. }
  71. }
  72. private void photoAndAll(ImageView imageView){
  73. PictureSelector.create(this)
  74. .openGallery(SelectMimeType.ofImage())
  75. .setImageEngine(GlideEngine.createGlideEngine()).setMaxSelectNum(1)
  76. .forResult(new OnResultCallbackListener<LocalMedia>() {
  77. @Override
  78. public void onResult(ArrayList<LocalMedia> result) {
  79. Log.e("leo","图片路径"+result.get(0).getPath());
  80. Log.e("leo","绝对路径"+result.get(0).getRealPath());
  81. Glide.with(MainActivity.this).load(result.get(0).getPath()).into(imageView);
  82. //将bitmap图片传入后端
  83. //imageUpLoad(result.get(0).getRealPath());
  84. SubmitPicture(result.get(0).getRealPath());
  85. }
  86. @Override
  87. public void onCancel() {
  88. Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
  89. }
  90. });
  91. }
  92. public static void imageUpLoad(String localPath) {
  93. MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
  94. OkHttpClient client = new OkHttpClient();
  95. MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
  96. File f = new File(localPath);
  97. builder.addFormDataPart("files", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
  98. final MultipartBody requestBody = builder.build();
  99. //构建请求
  100. final Request request = new Request.Builder()
  101. .url("后端接口")//地址
  102. .post(requestBody)//添加请求体
  103. .build();
  104. client.newCall(request).enqueue(new okhttp3.Callback() {
  105. @Override
  106. public void onFailure(Call call, IOException e) {
  107. System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
  108. }
  109. @Override
  110. public void onResponse(Call call, Response response) throws IOException {
  111. pmodel model = JSON.parseObject(response.body().string(), pmodel.class);
  112. Log.e("leo",JSON.toJSONString(model));
  113. pmodel model2 = JSON.parseObject(JSON.toJSONString(model), pmodel.class);
  114. }
  115. });
  116. }
  117. private void SubmitPicture(String path){
  118. String url = "后端接口";
  119. String token="token,没有要求则无需写入";
  120. RequestParams params = new RequestParams(url);
  121. params.addHeader("Authorization",token);
  122. //设置表单传送
  123. params.setMultipart(true);
  124. params.addBodyParameter("file",new File(path));
  125. params.addParameter("fileType","PICTURE");
  126. x.http().post(params, new Callback.CommonCallback<String>() {
  127. @Override
  128. public void onSuccess(String result) {
  129. Log.e("leo","2222"+params);
  130. Toast.makeText(MainActivity.this, "上传成功!", Toast.LENGTH_SHORT).show();
  131. Log.e("leo","返回"+result);
  132. pmodel model = JSON.parseObject(result, pmodel.class);
  133. PictureArr.add(model.getData().get(0).getUrl());
  134. }
  135. @Override
  136. public void onError(Throwable ex, boolean isOnCallback) {
  137. Log.e("leo","失败"+ex.getMessage());
  138. }
  139. @Override
  140. public void onCancelled(CancelledException cex) {
  141. }
  142. @Override
  143. public void onFinished() {
  144. }
  145. });
  146. }
  147. }

说明与解析:这边我们通过点击上传ImageView,则利用pictureSelector进行相册照片的选取,即photoAndAll方法进行选取,并且利用Glide(图片加载工具类)进行UI界面的显示,最后利用两种方法(imageUpload和SubmitPicture)提交上传图片,两种方法自行选取即可。

第三方pictureSelector的引入,以及Glide图片加载,xutils工具类的引入可参考如下:

  1. // PictureSelector 基础 (必须)
  2. implementation 'io.github.lucksiege:pictureselector:v3.0.5'
  3. // 图片压缩 (按需引入)
  4. implementation 'io.github.lucksiege:compress:v3.0.5'
  5. // 图片裁剪 (按需引入)
  6. implementation 'io.github.lucksiege:ucrop:v3.0.5'
  7. // 自定义相机 (按需引入)
  8. implementation 'io.github.lucksiege:camerax:v3.0.5'
  9. // 加载网络图片
  10. implementation 'com.github.bumptech.glide:glide:4.10.0'
  11. annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
  12. //网络请求
  13. implementation 'org.xutils:xutils:3.8.4'

xutils工具的使用需要创建自定义Application进行初始化

  1. public class BaseApplication extends Application {
  2. public static Handler sHandler;
  3. public static Context sContext = null;
  4. @Override
  5. public void onCreate() {
  6. super.onCreate();
  7. //初始化xUtils
  8. x.Ext.init(this);
  9. x.Ext.setDebug(BuildConfig.DEBUG);
  10. }
  11. }

Android图片上传下载总结与扩展

至此,简单的Android图片上传就完成了,图片的下载与只相似,只需要利用Xutils网络工具进行接口访问,拿到图片利用Glide或者其他方式进行显示和应用即可。

图片的上传下载与一些文件的上传下载类似,本demo只进行了单图上传的实例,实际上pictureSelector工具类十分强大,对于多图多选,图片压缩,视频选取都可以一句代码搞定,这样就可以很方便的实现多图上传,视频上传等其他功能,前提是后端小伙伴提供给你的接口支持相关上传下载。

感谢大家的阅读,有说明不到位的地方或者不足的地方欢迎指出评论

最后别忘记点个关注哦

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/530017
推荐阅读
相关标签