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

<?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:background="@color/coreGray"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
 
    <include layout="@layout/layout_title"/>
 
    <LinearLayout
        style="@style/LoginLayoutStyle"
 
        android:layout_width="match_parent">
 
        <TextView
            android:id="@ id/aaa"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="AAA:"
            android:textColor="@color/black60"
            android:textSize="20dp" />
 
        <com.tz.picturedemo.view.ClearEditText
            android:id="@ id/qs_username2"
            style="@style/EditTextStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入AAAA"
            android:inputType="text"
            android:lines="1"
            android:singleLine="true"
            android:textCursorDrawable="@null"
            app:regexType="name" />
    </LinearLayout>
    <LinearLayout
        style="@style/LoginLayoutStyle"
        android:layout_width="match_parent">
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="BBB:"
            android:textColor="@color/black60"
            android:textSize="20dp" />
 
        <com.tz.picturedemo.view.ClearEditText
            android:id="@ id/qs_username3"
            style="@style/EditTextStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入BBBB"
            android:inputType="text"
            android:lines="1"
            android:singleLine="true"
            android:textCursorDrawable="@null"
            app:regexType="name" />
    </LinearLayout>
    <LinearLayout
        style="@style/LoginLayoutStyle"
        android:layout_width="match_parent">
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="CCC:"
            android:textColor="@color/black60"
            android:textSize="20dp" />
 
        <com.tz.picturedemo.view.ClearEditText
            android:id="@ id/qs_username"
            style="@style/EditTextStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入CCCC"
            android:inputType="text"
            android:lines="1"
            android:singleLine="true"
            android:textCursorDrawable="@null"
            app:regexType="name" />
    </LinearLayout>
 
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="上传图片"
        android:textColor="@color/black60"
        android:padding="10dp"
        android:textSize="20sp"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="20dp"
        android:orientation="horizontal">
 
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">
            <ImageView
                android:id="@ id/picture1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_add_image"/>
 
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="10dp"
                android:text="正面"
                android:textColor="@color/black60"
                android:textSize="18sp" />
 
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">
            <ImageView
                android:id="@ id/picture2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_add_image"/>
 
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="10dp"
                android:text="侧面"
                android:textColor="@color/black60"
                android:textSize="18sp" />
 
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="vertical">
            <ImageView
                android:id="@ id/picture3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_add_image"/>
 
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="10dp"
                android:text="反面"
                android:textColor="@color/black60"
                android:textSize="18sp" />
        </LinearLayout>
 
    </LinearLayout>
 
    <Button
        android:id="@ id/makesure"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="提交"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="50dp"
        android:textSize="20dp"
        android:textColor="@color/white"
        android:background="@drawable/share_item_blue_bg"
        />
</LinearLayout>

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

Demo功能核心代码 MainActivity

package com.tz.picturedemo;
 
import static com.luck.picture.lib.config.SelectMimeType.ofImage;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    private ImageView mPicture1;
    private ImageView mPicture2;
    private ImageView mPicture3;
    private  List<String>  PictureArr=new ArrayList<>();
    private Button mBtn;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN );//这句让view 顶到顶
        getWindow().setStatusBarColor(Color.TRANSPARENT);//这句让状态栏透明
        initVew();
    }
 
    private void initVew() {
        mPicture1=findViewById(R.id.picture1);
        mPicture2=findViewById(R.id.picture2);
        mPicture3=findViewById(R.id.picture3);
        mBtn=findViewById(R.id.makesure);
 
        mPicture1.setOnClickListener(this);
        mPicture2.setOnClickListener(this);
        mPicture3.setOnClickListener(this);
        mBtn.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.picture1:
                photoAndAll(mPicture1);
                break;
            case R.id.picture2:
                photoAndAll(mPicture2);
            break;
            case R.id.picture3:
                photoAndAll(mPicture3);
                break;
            case R.id.makesure:
 
                break;
        }
    }
 
 
    private  void photoAndAll(ImageView imageView){
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine()).setMaxSelectNum(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        Log.e("leo","图片路径" result.get(0).getPath());
                        Log.e("leo","绝对路径" result.get(0).getRealPath());
                        Glide.with(MainActivity.this).load(result.get(0).getPath()).into(imageView);
                        //将bitmap图片传入后端
                        //imageUpLoad(result.get(0).getRealPath());
                        SubmitPicture(result.get(0).getRealPath());
                    }
                    @Override
                    public void onCancel() {
                        Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
                    }
                });
    }
 
    public static void imageUpLoad(String localPath) {
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        OkHttpClient client = new OkHttpClient();
 
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
 
        File f = new File(localPath);
        builder.addFormDataPart("files", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
        final MultipartBody requestBody = builder.build();
        //构建请求
        final Request request = new Request.Builder()
                .url("后端接口")//地址
                .post(requestBody)//添加请求体
                .build();
 
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("上传失败:e.getLocalizedMessage() = "   e.getLocalizedMessage());
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
 
                pmodel model = JSON.parseObject(response.body().string(), pmodel.class);
                Log.e("leo",JSON.toJSONString(model));
                pmodel model2 = JSON.parseObject(JSON.toJSONString(model), pmodel.class);
              
            }
        });
    }
 
 
    private void  SubmitPicture(String path){
        String  url = "后端接口";
        String token="token,没有要求则无需写入";
        RequestParams params = new RequestParams(url);
        params.addHeader("Authorization",token);
 
        //设置表单传送
        params.setMultipart(true);
        params.addBodyParameter("file",new File(path));
        params.addParameter("fileType","PICTURE");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("leo","2222" params);
                Toast.makeText(MainActivity.this, "上传成功!", Toast.LENGTH_SHORT).show();
                Log.e("leo","返回" result);
                pmodel model = JSON.parseObject(result, pmodel.class);
                PictureArr.add(model.getData().get(0).getUrl());
            }
 
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("leo","失败" ex.getMessage());
            }
 
            @Override
            public void onCancelled(CancelledException cex) {
 
            }
 
            @Override
            public void onFinished() {
            }
        });
    }
 
}

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

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

 // PictureSelector 基础 (必须)
    implementation 'io.github.lucksiege:pictureselector:v3.0.5'
    // 图片压缩 (按需引入)
    implementation 'io.github.lucksiege:compress:v3.0.5'
    // 图片裁剪 (按需引入)
    implementation 'io.github.lucksiege:ucrop:v3.0.5'
    // 自定义相机 (按需引入)
    implementation 'io.github.lucksiege:camerax:v3.0.5'
    //    加载网络图片
    implementation 'com.github.bumptech.glide:glide:4.10.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
    //网络请求
    implementation 'org.xutils:xutils:3.8.4'

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

public class BaseApplication extends Application {
    public static Handler sHandler;
    public static Context sContext = null;
    @Override
    public void onCreate() {
        super.onCreate();
 
        //初始化xUtils
        x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG);
 
    }

}

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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持Devmax。

Android开发实现图片的上传下载的更多相关文章

  1. html5 canvas合成海报所遇问题及解决方案总结

    这篇文章主要介绍了html5 canvas合成海报所遇问题及解决方案总结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Html5 video标签视频的最佳实践

    这篇文章主要介绍了Html5 video标签视频的最佳实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  3. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  4. HTML5在微信内置浏览器下右上角菜单的调整字体导致页面显示错乱的问题

    HTML5在微信内置浏览器下,在右上角菜单的调整字体导致页面显示错乱的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

  5. ios – containerURLForSecurityApplicationGroupIdentifier:在iPhone和Watch模拟器上给出不同的结果

    我使用默认的XCode模板创建了一个WatchKit应用程序.我向iOSTarget,WatchkitAppTarget和WatchkitAppExtensionTarget添加了应用程序组权利.(这是应用程序组名称:group.com.lombax.fiveminutes)然后,我尝试使用iOSApp和WatchKitExtension访问共享文件夹URL:延期:iOS应用:但是,测试NSURL

  6. Ionic – Splash Screen适用于iOS,但不适用于Android

    我有一个离子应用程序,其中使用CLI命令离子资源生成的启动画面和图标iOS版本与正在渲染的启动画面完美配合,但在Android版本中,只有在加载应用程序时才会显示白屏.我检查了config.xml文件,所有路径看起来都是正确的,生成的图像出现在相应的文件夹中.(我使用了splash.psd模板来生成它们.我错过了什么?这是config.xml文件供参考,我觉得我在这里做错了–解决方法在config.xml中添加以下键:它对我有用!

  7. ios – 无法启动iPhone模拟器

    /Library/Developer/CoreSimulator/Devices/530A44CB-5978-4926-9E91-E9DBD5BFB105/data/Containers/Bundle/Application/07612A5C-659D-4C04-ACD3-D211D2830E17/ProductName.app/ProductName然后,如果您在Xcode构建设置中选择标准体系结构并再次构建和运行,则会产生以下结果:dyld:lazysymbolbindingFailed:Symbol

  8. Xamarin iOS图像在Grid内部重叠

    heyo,所以在Xamarin我有一个使用并在其中包含一对,所有这些都包含在内.这在Xamarin.Android中看起来完全没问题,但是在Xamarin.iOS中,图像与标签重叠.我不确定它的区别是什么–为什么它在Xamarin.Android中看起来不错但在iOS中它的全部都不稳定?

  9. 在iOS上向后播放HTML5视频

    我试图在iPad上反向播放HTML5视频.HTML5元素包括一个名为playbackRate的属性,它允许以更快或更慢的速率或相反的方式播放视频.根据Apple’sdocumentation,iOS不支持此属性.通过每秒多次设置currentTime属性,可以反复播放,而无需使用playbackRate.这种方法适用于桌面Safari,但似乎在iOS设备上的搜索限制为每秒1次更新–在我的情况下太慢了.有没有办法在iOS设备上向后播放HTML5视频?解决方法iOS6Safari现在支持playbackRat

  10. 使用 Swift 语言编写 Android 应用入门

    Swift标准库可以编译安卓armv7的内核,这使得可以在安卓移动设备上执行Swift语句代码。做梦,虽然Swift编译器可以胜任在安卓设备上编译Swift代码并运行。这需要的不仅仅是用Swift标准库编写一个APP,更多的是你需要一些框架来搭建你的应用用户界面,以上这些Swift标准库不能提供。简单来说,构建在安卓设备上使用的Swiftstdlib需要libiconv和libicu。通过命令行执行以下命令:gitclonegit@github.com:SwiftAndroid/libiconv-libi

随机推荐

  1. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Android单选按钮RadioButton的使用详解

    今天小编就为大家分享一篇关于Android单选按钮RadioButton的使用详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  3. 解决android studio 打包发现generate signed apk 消失不见问题

    这篇文章主要介绍了解决android studio 打包发现generate signed apk 消失不见问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

  4. Android 实现自定义圆形listview功能的实例代码

    这篇文章主要介绍了Android 实现自定义圆形listview功能的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 详解Android studio 动态fragment的用法

    这篇文章主要介绍了Android studio 动态fragment的用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. Android用RecyclerView实现图标拖拽排序以及增删管理

    这篇文章主要介绍了Android用RecyclerView实现图标拖拽排序以及增删管理的方法,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下

  7. Android notifyDataSetChanged() 动态更新ListView案例详解

    这篇文章主要介绍了Android notifyDataSetChanged() 动态更新ListView案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  8. Android自定义View实现弹幕效果

    这篇文章主要为大家详细介绍了Android自定义View实现弹幕效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. Android自定义View实现跟随手指移动

    这篇文章主要为大家详细介绍了Android自定义View实现跟随手指移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android实现多点触摸操作

    这篇文章主要介绍了Android实现多点触摸操作,实现图片的放大、缩小和旋转等处理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部