美文网首页
Android Studio 上传文件实例_RETROFIT

Android Studio 上传文件实例_RETROFIT

作者: 牧区叔叔 | 来源:发表于2020-09-18 19:41 被阅读0次

效果(服务器是自己的,地址自己找)

image.png

思路

1、添加依赖

 implementation 'com.squareup.retrofit2:retrofit:2.4.0'
 implementation "io.reactivex.rxjava2:rxjava:2.1.3" 
 implementation "io.reactivex.rxjava2:rxandroid:2.0.1" 
 implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0' 
 implementation "com.github.bumptech.glide:glide:4.8.0"
 implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

2、添加权限

网络、读写权限。

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

3、XML布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/upload_bt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="OKHTTP上传" />

    <Button
        android:id="@+id/retro_upload_bt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/upload_bt"
        android:text="Retrofit上传" />
    <TextView
        android:id="@+id/upload_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/retro_upload_bt"
        android:gravity="center"
        android:text="显示文本"
        android:textSize="18sp" />
    <ImageView
        android:id="@+id/upload_image"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@id/upload_tv"
        android:layout_centerHorizontal="true"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_launcher_background" />
</RelativeLayout>

4、动态权限获取

ActivityCompat.requestPermissions(参数1,参数2,参数3),参数3自定义即可,这个参数体现在onRequestPermissionsResult()重写的函数。

 if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            reUpLoadFile();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 202);
        }

5、Retrofit上传文件

 //  retrofit 对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(UpLoadServer.baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //接口对象
        UpLoadServer server = retrofit.create(UpLoadServer.class);

        //获取post请求参数 key  和  file
        file = new File(Environment.getExternalStorageDirectory() + "/Pictures/Screenshots/a.png");
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), "1001");
        MultipartBody.Part mulbody = MultipartBody.Part.createFormData("file", this.file.getName(), requestBody);//获取上传文件的请求体

        //call对象
        final Observable<UpLoadBean> upLoad = server.upLoad(body,mulbody);
        //call执行请求
        upLoad.subscribeOn(Schedulers.io())//子线程
                .observeOn(AndroidSchedulers.mainThread())  //主线程
                .subscribe(new Observer<UpLoadBean>() {//订阅返回数据
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UpLoadBean upLoadBean) {
                        if (upLoadBean != null) {
                            int code = upLoadBean.getCode();
                            String s = String.valueOf(code);
                            if (s.equals("200")) {
                                Toast.makeText(MainActivity.this, "加载成功" + upLoadBean.getCode(), Toast.LENGTH_SHORT).show();
                                uploadTv.setText(upLoadBean.getRes());
                                Glide.with(MainActivity.this).load(upLoadBean.getData().getUrl()).into(uploadImage);
                            } else {
                                Toast.makeText(MainActivity.this, "状态码有误" + upLoadBean.getCode(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(MainActivity.this, "上传失败" + upLoadBean.getCode(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(MainActivity.this, "解析失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

完整代码

MainActivity(OK上传也在其中没删除)

package com.mooc.uploadfile;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

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

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Multipart;

public class MainActivity extends AppCompatActivity {

    private Button uploadBt;
    private Button reUploadBt;
    private TextView uploadTv;
    private ImageView uploadImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        okUPLoad();//OK 上传
        reTrofitLoad();//retrofit上传
    }

    private void reTrofitLoad() {
        reUploadBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPermission_retrofit();//检查危险权限
            }
        });
    }

    private void okUPLoad() {
        uploadBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPermission();//检查危险权限
            }
        });
    }

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            try {
                upLodeFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 201);
        }
    }

    private void checkPermission_retrofit() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            reUpLoadFile();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 202);
        }
    }

    private void reUpLoadFile() {
        //  retrofit 对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(UpLoadServer.baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //接口对象
        UpLoadServer server = retrofit.create(UpLoadServer.class);

        //获取post请求参数 key  和  file
        file = new File(Environment.getExternalStorageDirectory() + "/Pictures/Screenshots/a.png");
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), "1001");
        MultipartBody.Part mulbody = MultipartBody.Part.createFormData("file", this.file.getName(), requestBody);//获取上传文件的请求体

        //call对象
        final Observable<UpLoadBean> upLoad = server.upLoad(body,mulbody);
        //call执行请求
        upLoad.subscribeOn(Schedulers.io())//子线程
                .observeOn(AndroidSchedulers.mainThread())  //主线程
                .subscribe(new Observer<UpLoadBean>() {//订阅返回数据
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UpLoadBean upLoadBean) {
                        if (upLoadBean != null) {
                            int code = upLoadBean.getCode();
                            String s = String.valueOf(code);
                            if (s.equals("200")) {
                                Toast.makeText(MainActivity.this, "加载成功" + upLoadBean.getCode(), Toast.LENGTH_SHORT).show();
                                uploadTv.setText(upLoadBean.getRes());
                                Glide.with(MainActivity.this).load(upLoadBean.getData().getUrl()).into(uploadImage);
                            } else {
                                Toast.makeText(MainActivity.this, "状态码有误" + upLoadBean.getCode(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(MainActivity.this, "上传失败" + upLoadBean.getCode(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(MainActivity.this, "解析失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e("tag", "onRequestPermissionsResult: " + requestCode);
        if (grantResults != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "用户授权", Toast.LENGTH_SHORT).show();
            try {
                switch (requestCode) {
                    case 201:
                        upLodeFile();
                        break;
                    case 202:
                        break;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "用户未授权", Toast.LENGTH_SHORT).show();
        }
    }

    private File file;

    private void upLodeFile() throws IOException {
        file = new File(Environment.getExternalStorageDirectory() + "/Pictures/Screenshots/a.png");//获取目录(不加后面的字符串是你的根目录+后面是继续找的意思)
        getFileLog();
        //ok上传
        /**
         * ok上传文件实例
         * 由于服务器暂停维护,接口无法访问
         * 代码就这些
         */
        //创建OK
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        //请求体
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("key", "1001")                      //post请求Key,value
                .addFormDataPart("file", file.getName(), requestBody)     //post请求Key,value
                .build();
        //构建请求
        Request request = new Request.Builder()
//                .url("http://yun918.cn/study/public/index.php/file_upload.php")
                .url("http://yun918.cn/study/public/file_upload.php")
                .post(body)
                .build();
        //call对象
        Call call = okHttpClient.newCall(request);
        //call执行请求
        call.enqueue(new Callback() {   //异步
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("tag", "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                final UpLoadBean upLoadBean = new Gson().fromJson(json, UpLoadBean.class);
                if (!TextUtils.isEmpty(json)) {
                    int code = upLoadBean.getCode();
                    String str = String.valueOf(code);
                    if (str.equals("200")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                uploadTv.setText(upLoadBean.getRes());
                                Glide.with(MainActivity.this).load(upLoadBean.getData().getUrl()).into(uploadImage);
                            }
                        });
                    } else {
                        Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private void getFileLog() {
        File absoluteFile = file.getAbsoluteFile();
        String absolutePath = file.getAbsolutePath();
        File canonicalFile = null;
        try {
            canonicalFile = file.getCanonicalFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String canonicalPath = null;
        try {
            canonicalPath = file.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long freeSpace = file.getFreeSpace();
        String parent = file.getParent();
        File parentFile = file.getParentFile();
        String path = file.getPath();
        long totalSpace = file.getTotalSpace();
        long usableSpace = file.getUsableSpace();
        Log.e("tag", "absoluteFile: " + absoluteFile
                + "\t\n" + "absolutePath: " + absolutePath
                + "\t\n" + "canonicalFile: " + canonicalFile
                + "\t\n" + "canonicalPath: " + canonicalPath
                + "\t\n" + "freeSpace: " + freeSpace
                + "\t\n" + "parent: " + parent
                + "\t\n" + "parentFile: " + parentFile
                + "\t\n" + "path: " + path
                + "\t\n" + "totalSpace: " + totalSpace
                + "\t\n" + "usableSpace: " + usableSpace);
    }

    private void initView() {
        uploadBt = (Button) findViewById(R.id.upload_bt);
        reUploadBt = (Button) findViewById(R.id.retro_upload_bt);
        uploadTv = (TextView) findViewById(R.id.upload_tv);
        uploadImage = (ImageView) findViewById(R.id.upload_image);


    }
}

接口

package com.mooc.uploadfile;


import io.reactivex.Observable;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public
/**
 * @auther Administrator
 * @date 2020/9/18
 * @time 18:50
 */
interface UpLoadServer {
    String baseUrl = "http://yun918.cn/study/";
    @Multipart
    @POST("public/file_upload.php")
    Observable<UpLoadBean> upLoad(@Part("key")RequestBody key,@Part MultipartBody.Part file);

}

相关文章

网友评论

      本文标题:Android Studio 上传文件实例_RETROFIT

      本文链接:https://www.haomeiwen.com/subject/ajzjyktx.html