如何在Android中上传10 MB的文件?

时间:2017-01-11 08:44:27

标签: android retrofit

我在Android中使用文件选择器创建了一个程序我选择了一个文件而不是之后,我已经上传到我的服务器一切正常。

但是我想只上传10mb文件或想要一个简单的程序,如果我的文件大小超过10mb,那么文件无法在Android中选择或上传。

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == PICK_FILE_REQUEST){
                if(data == null){
                    //no data present
                    return;
                }


                Uri selectedFileUri = data.getData();
                selectedFilePath = FilePath.getPath(getActivity(),selectedFileUri);

                Log.i(TAG,"Selected File Path:" + selectedFilePath);

                if(selectedFilePath != null && !selectedFilePath.equals("")){
                    tvFileName.setText(selectedFilePath);

                }else{
                    Toast.makeText(getActivity(),"Cannot upload file to server", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }




    // Uploading Image/Video
    private void uploadFile() {
        dialog = ProgressDialog.show(getActivity(), "", "Uploading File...", true);


        // Map is used to multipart the file using okhttp3.RequestBody
        Map<String, RequestBody> map = new HashMap<>();
        File file = new File(selectedFilePath);
        String name=tv_name.getText().toString();
        String email=tv_email.getText().toString();
        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        RequestBody requestBody1=RequestBody.create(MediaType.parse("text/plain"),name);
        RequestBody requestBody2=RequestBody.create(MediaType.parse("text/plain"),email);
        map.put("file\"; filename=\"" + selectedFilePath + "\"", requestBody);
        map.put("name\"; username=\"" + name+ "\"", requestBody1 );
        map.put("email\"; email=\"" + email+ "\"", requestBody2 );

1 个答案:

答案 0 :(得分:0)

您可以使用文件length()来获取文件大小(以字节为单位),并有一个条件来检查它是否超过10mb。

例如

long maxLength = 10000000;
File file = .....;

if(file.length() > maxLength){
    //failed length validation
}else{
    //continue
}