我想将 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/