How to upload a PDF file to server in android?

蹲街弑〆低调 提交于 2019-12-02 08:28:10

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);

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());
            }
        }

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