上传/下载特定文件到/从网络服务器上传到手机android studio

时间:2018-04-25 05:33:13

标签: android android-studio file-upload download

如何上传特定部分的文件,并将特定于某个部分的文件从我的网络服务器下载到我的Android应用程序?每当我点击显示服务器上的文件时,它都会显示所有文件。我希望它只显示某个部分的特定文件。

这是我的代码:

上传文件

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

    button = (ImageButton) findViewById(R.id.imageButton);


    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
            return;
        }
    }

    enable_button();
}

private void enable_button() {

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new MaterialFilePicker()
                    .withActivity(ProfessorUploadFileToServerActivity.this)
                    .withRequestCode(10)
                    .start();
        }
    });
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if(requestCode == 100 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){
        enable_button();
    }else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
        }
    }
}

@Override
public void onBackPressed(){
    Intent intent = new Intent(ProfessorUploadFileToServerActivity.this,ProfessorMainMenuActivity.class);
    ProfessorUploadFileToServerActivity.this.startActivity(intent);
    finish();
}

ProgressDialog progress;

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if(requestCode == 10 && resultCode == RESULT_OK){

        progress = new ProgressDialog(ProfessorUploadFileToServerActivity.this);
        progress.setTitle("Uploading");
        progress.setMessage("Please wait...");
        progress.show();

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {

                File f  = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
                String content_type  = getMimeType(f.getPath());

                String file_path = f.getAbsolutePath();
                OkHttpClient client = new OkHttpClient();
                RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);

                RequestBody request_body = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("type",content_type)
                        .addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
                        .build();

                Request request = new Request.Builder()
                        .url("https://orwell-systems.000webhostapp.com/UploadToServer.php")
                        .post(request_body)
                        .build();

                try {
                    Response response = client.newCall(request).execute();

                    if(!response.isSuccessful()){
                        throw new IOException("Error : "+response);
                    }

                    progress.dismiss();

                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        });
        t.start();
    }
}

private String getMimeType(String path) {

    String extension = MimeTypeMap.getFileExtensionFromUrl(path);

    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}

我的下载文件

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

    permission_check();
}

private void permission_check() {
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
            return;
        }
    }
    initialize();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
        initialize();
    }else {
        permission_check();
    }
}

@Override
public void onBackPressed() {

    Intent intent = new Intent(StudentDownloadFileActivity.this,StudentMainMenuActivity.class);
    StudentDownloadFileActivity.this.startActivity(intent);
    finish();
}

private void initialize() {

    button = (Button) findViewById(R.id.button);
    listView = (ListView) findViewById(R.id.listView);
    arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,files_on_server);



    listView.setAdapter(arrayAdapter);
    handler = new Handler();

    progressDialog = new ProgressDialog(this);
    progressDialog.setTitle("Downloading...");
    progressDialog.setMax(100);
    progressDialog.setCancelable(false);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("https://orwell-systems.000webhostapp.com/DownloadFromServer.php?list_files").build();

                    Response response = null;
                    try {
                        response = client.newCall(request).execute();
                        JSONArray array = new JSONArray(response.body().string());

                        for (int i = 0; i <array.length(); i++){

                            String file_name = array.getString(i);

                            if(files_on_server.indexOf(file_name) == -1)
                                files_on_server.add(file_name);
                        }


                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                arrayAdapter.notifyDataSetChanged();
                            }
                        });


                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            t.start();
        }
    });

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            selected_file = ((TextView)view).getText().toString();

            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {


                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("https://orwell-systems.000webhostapp.com//uploads/" + selected_file).build();

                    Response response = null;
                    try {
                        response = client.newCall(request).execute();
                        float file_size = response.body().contentLength();

                        BufferedInputStream inputStream = new BufferedInputStream(response.body().byteStream());
                        OutputStream stream = new FileOutputStream(Environment.getExternalStorageDirectory()+"/Download/"+selected_file);

                        byte[] data = new byte[8192];
                        float total = 0;
                        int read_bytes=0;

                        handler.post(new Runnable() {
                            @Override
                            public void run() {

                                progressDialog.show();
                            }
                        });


                        while ( (read_bytes = inputStream.read(data)) != -1 ){

                            total = total + read_bytes;
                            stream.write( data, 0, read_bytes);
                            progressDialog.setProgress((int) ((total / file_size)*100));

                        }

                        progressDialog.dismiss();
                        stream.flush();
                        stream.close();
                        response.body().close();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    });
}

提前谢谢

0 个答案:

没有答案