Upload pdf file from android to php

2019-03-31 23:55发布

问题:

I want to upload pdf or doc file from android device to php. I got the filePath in onActivityResult method.

Uri selectedFileUri = data.getData();
 String path = selectedFileUri.getPath();

I want to know that if there is any method by which I can send file to server? Iam sending image file to server by encoding it to base64 but how can I upload pdf or doc.

回答1:

You can send it as byte array btw

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    // show error
}

And in your php file you can get it with $_FILES.
If you want to add the value name then you can use multipart

HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

HttpPost httppost = new HttpPost("http://***.***.***.***/upload.php");
File file = new File("/sdcard/randyka.pdf");

MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("your_file", cbFile);

httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

System.out.println(response.getStatusLine());

And your php will be like

<?php $_FILES['your_file']?>


回答2:

We have used Retrofit Library for uploading PDF file on Server. This is the best way to upload PDF file in android programmatically.

This is the Interface declaration:

@POST("/api/uploadcontroller)

Response uploadPdf(@Body TypedFile file);

Make the call in RestAdapter of the Retrofit API:->

restAdapter.create(RestApiInterface.class) // ^ interface

.uploadPdf(new TypedFile(“application/pdf”, //MIME TYPE
                            new File(pdfFilePath)));// File