将 pdf 文件从 android 上传到 php

Upload pdf file from android to php

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

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

我想知道有什么方法可以发送文件到服务器吗?我正在通过将图像文件编码为 base64 将其发送到服务器,但我如何上传 pdf 或 doc。

顺便说一句,您可以将其作为字节数组发送

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']?>

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

这是接口声明:

@POST("/api/uploadcontroller)

Response uploadPdf(@Body TypedFile file);

在Retrofit的RestAdapter中调用API:->

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

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