Android简单文件上传
创始人
2024-10-08 12:30:56
0

要实现Android简单文件上传,可以使用以下解决方法:

  1. 添加文件上传所需的依赖库

在项目的build.gradle文件中添加以下依赖库:

implementation 'com.squareup.okhttp3:okhttp:3.12.13'
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.13'
  1. 创建一个上传文件的网络请求
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

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

public class FileUploader {

    public static final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
    private static final String BASE_URL = "http://example.com/upload";
    private OkHttpClient client;

    public FileUploader() {
        client = new OkHttpClient();
    }

    public String uploadFile(String filePath) throws IOException {
        File file = new File(filePath);

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_JPEG, file))
                .build();

        Request request = new Request.Builder()
                .url(BASE_URL)
                .post(requestBody)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}
  1. 在Activity或Fragment中调用文件上传方法
public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_FILE_PICKER = 1;
    private FileUploader fileUploader;

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

        fileUploader = new FileUploader();

        // 点击按钮选择文件并上传
        Button uploadButton = findViewById(R.id.upload_button);
        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                startActivityForResult(intent, REQUEST_CODE_FILE_PICKER);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_FILE_PICKER && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = getRealPathFromUri(uri);
            uploadFile(filePath);
        }
    }

    private String getRealPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }

    private void uploadFile(final String filePath) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final String response = fileUploader.uploadFile(filePath);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 文件上传成功后的处理
                            Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (final IOException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 文件上传失败后的处理
                            Toast.makeText(MainActivity.this, "上传失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }
}

上述代码示例中,MainActivity中的uploadFile方法用于选择文件并调用FileUploader的uploadFile方法进行上传。在FileUploader的uploadFile方法中,首先构建一个MultipartBody对象,将文件添加到请求体中,然后构建一个POST请求并使用OkHttpClient发送请求。最后,通过Response对象获取服务端返回的响应数据。

请注意替换BASE_URL为实际的上传接口地址,并确保在AndroidManifest.xml中添加了对文件读取的权限。

相关内容

热门资讯

透视神器!wepoker有机器... 透视神器!wepoker有机器人吗,wepoker辅助插件功能,指南书教程(竟然是有挂)-哔哩哔哩w...
透视好牌!wepoker数据分... 透视好牌!wepoker数据分析,wepokerplus辅助,烘培教程(切实是真的挂)-哔哩哔哩1、...
透视安装!wepokerplu... 您好,大菠萝手游辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家...
透视了解!pokemmo脚本辅... 透视了解!pokemmo脚本辅助器下载,wepoker轻量版辅助,秘籍教程(都是存在有挂)-哔哩哔哩...
透视了解!wepoker免费透... 透视了解!wepoker免费透视脚本,德普之星辅助器app,方式教程(切实是真的挂)-哔哩哔哩暗藏猫...
透视规律!拱趴大菠萝机器人,x... 透视规律!拱趴大菠萝机器人,xpoker怎么辅助,技法教程(好像存在有挂)-哔哩哔哩1、拱趴大菠萝机...
透视了解!wepoker透视功... 透视了解!wepoker透视功能下载,淘宝买wepoker透视有用吗,办法教程(切实真的是有挂)-哔...
透视黑科技!德普之星怎么设置埋... 透视黑科技!德普之星怎么设置埋牌,we-poker靠谱吗,模板教程(竟然真的有挂)-哔哩哔哩1、德普...
透视挂透视!epoker底牌透... 透视挂透视!epoker底牌透视,aapoker怎么提高中牌率,方案教程(其实真的是有挂)-哔哩哔哩...
透视好友!we-poker辅助... 透视好友!we-poker辅助器,wpk辅助哪里买,讲义教程(本来是真的挂)-哔哩哔哩1、起透看视 ...