将pdf文件从android上传到php

时间:2015-03-09 09:01:07

标签: android file-upload

我想从android设备上传pdf或doc文件到php。  我在onActivityResult方法中获得了filePath。

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

我想知道如果有任何方法可以将文件发送到服务器?我通过将图像文件编码为base64将图像文件发送到服务器但是如何上传pdf或doc。

2 个答案:

答案 0 :(得分:1)

您可以将其作为字节数组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
}

在您的php文件中,您可以使用$ _FILES获取它 如果要添加值名称,则可以使用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());

你的php就像

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

答案 1 :(得分:1)

我们已使用Retrofit Library在服务器上上传PDF文件。这是以编程方式在android上传PDF文件的最佳方式。

这是界面声明:

@POST("/api/uploadcontroller)

Response uploadPdf(@Body TypedFile file);

在Retrofit API的RestAdapter中进行调用: - &gt;

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

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