android - 将pdf文件从android上传到php

标签 android file-upload

我想将 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']?>

关于android - 将pdf文件从android上传到php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28938199/

相关文章:

安卓; ListView 是显示多个独立进度条的最佳方法吗?

iphone - 使用 PhoneGap + iPhone 上传文件

javascript - 如何判断 POST 请求是否包含要在 Sails.js 中上传的文件?

Android Studio : Pair devices over Wi-Fi - This system does not meet requirements to support Wi-Fi pairing

Android Studio 和 9-patch 错误

android - 根据 ViewPager Android 显示菜单项

android - 如何从文件资源管理器在我的应用程序中打开单个图像

jquery - 如何使用 jQuery 从文件输入中捕获文件名?

java - S3文件上传困惑

javascript - 为什么 'file.size'需要很多时间,如何减少时间?