How to upload a PDF file to server in android?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 20:02:51

问题


I referred some previously asked questions but not get proper solution.I am creating an Application and want to send PDF file by selecting it from File Manager.

Thanks any type of help would appreciated.


回答1:


Only you have to change this lines of code when you have to select PDF file from gallery . intent.setType("application/pdf") this will search only PDF files from gallery.

    Intent intent = new Intent();
    intent.setType("application/pdf");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PDF);



回答2:


Use Okhttp library like this, it is the simplest way to do it. But You have to change your server(API or PHP) code according to this.

    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("variable", fileName1,
                    RequestBody.create(MediaType.parse(fileType1), file))
            .addFormDataPart("key", "")


            .build();
    Request request = new Request.Builder().url("server url goes here").post(requestBody).build();
    okhttp3.Call call = client.newCall(request);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            System.out.println("Registration Error" + e.getMessage());
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {

            try {
                String resp = response.body().string();
                Log.v("Docs", resp);

            } catch (IOException e) {
                System.out.println("Exception caught" + e.getMessage());
            }
        }

    });


来源:https://stackoverflow.com/questions/44133076/how-to-upload-a-pdf-file-to-server-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!