【问题标题】:Upload pdf file from android to php将pdf文件从android上传到php
【发布时间】:2015-05-10 09:13:43
【问题描述】:

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

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

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

【问题讨论】:

  • 这是正常的文件上传操作。您在服务器端使用任何 php 框架吗?检查此链接stackoverflow.com/a/4126746/3843374
  • 是的,我在服务器端使用 php。我可以对付它。但我想知道我应该从 android 设备发送什么
  • Iam sending image file to server by encoding it to base64 but how can I upload pdf or doc.。您不必更改任何代码。至少如果您没有使用 Bitmap 或 BitmapFactory 上传该图像文件。文件只是一个文件,因此它始终有效。

标签: android file-upload


【解决方案1】:

你可以把它作为字节数组发送

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

【讨论】:

  • 我在 android 中有完整的文件路径。我可以把它放在哪里。假设“mnt/sdcard/documents/file.pdf”
  • File file = new File("mnt/sdcard/documents/file.pdf");
  • 我可以用namevaluepair发送吗
  • 您的文件名。即你的文件名是 Randyka.pdf 然后$_FILES['randyka.pdf']
  • 最后一个问题。如何从路径中获取文件名???请告诉我,我即将完成
【解决方案2】:

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

这是接口声明:

@POST("/api/uploadcontroller)

Response uploadPdf(@Body TypedFile file);

在 Retrofit API 的 RestAdapter 中调用:->

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

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

【讨论】:

    猜你喜欢
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多