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

Android Studio 上传文件实例_OKHTTP

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

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

image.png

思路

1、添加依赖

 implementation 'com.squareup.okhttp3:okhttp:3.11.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="上传" />
    <TextView
        android:id="@+id/upload_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/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){
            try {
                upLodeFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},201);
        }

5、OKHTTP上传文件

 //创建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", "1")                      //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();
                    }
                }
            }
        });

完整代码

MainActivity

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 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 MainActivity extends AppCompatActivity {

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

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

        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);
        }
    }
    @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 {
                upLodeFile();
            } 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", "1")                      //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);
        uploadTv = (TextView) findViewById(R.id.upload_tv);
        uploadImage = (ImageView) findViewById(R.id.upload_image);
    }
}

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="上传" />
    <TextView
        android:id="@+id/upload_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/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>

Bean

package com.mooc.uploadfile;

public
/**
 * @auther Administrator
 * @date 2020/9/18
 * @time 16:23
 */
class UpLoadBean {

    /**
     * code : 200
     * res : 上传文件成功
     * data : {"url":"http://yun918.cn/study/public/uploadfiles/123/944365-ee747d1e331ed5a4.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/123/944365-ee747d1e331ed5a4.png
         */

        private String url;

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}

相关文章

网友评论

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

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