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透视脚本免费下载pc这款游戏可以开挂的,确实是有挂的,需要了解加微【136704...
透视模拟器!sohoo竞技联盟... 透视模拟器!sohoo竞技联盟辅助器(透视)都是存在有挂(详细辅助解说技巧)进入游戏-大厅左侧-新手...
我来教大家!pokemmo脚本... 这是一款非常优秀的wepoker透视底牌脚本 ia辅助检测软件,能够让你了解到wepoker透视底牌...
透视真的!pokemmo脚本最... 透视真的!pokemmo脚本最新版(透视)一贯有挂(详细辅助力荐教程)辅助器中分为三种模型:软件透明...
揭秘真相!红龙poker辅助器... 揭秘真相!红龙poker辅助器免费观看,wepokerplus辅助,详细教程(有挂方法)1、点击下载...
透视有挂!pokemmo辅助官... 透视有挂!pokemmo辅助官网(透视)切实是真的有挂(详细辅助科技教程)1、该软件可以轻松地帮助玩...
总算了解!aapoker发牌逻... 总算了解!aapoker发牌逻辑,拱趴大菠萝万能挂,力荐教程(有挂技巧)这是由厦门游乐互动科技有限公...
透视挂透视!德扑圈透视挂(透视... 透视挂透视!德扑圈透视挂(透视)确实存在有挂(详细辅助德州教程)1、玩家可以在软件透明挂俱乐部对游戏...
指导大家!wepoker透视辅... 指导大家!wepoker透视辅助下载,wepoker游戏的安装教程,靠谱教程(有挂软件);实战中需综...
透视科技!哈糖大菠萝破解器(透... 透视科技!哈糖大菠萝破解器(透视)一贯有挂(详细辅助攻略教程);1、系统规律教程、辅助透视等服务,为...