Android简单文件上传
创始人
2024-10-08 12:32:10
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中添加了对文件读取的权限。

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...