gpt4 book ai didi

php - Android:通过 HttpResponse 从 PHP 服务器获取文件

转载 作者:行者123 更新时间:2023-11-30 02:37:24 25 4
gpt4 key购买 nike

我的 android 应用程序成功地将文件发送到远程 php 服务器。直到知道服务器通过发回一个简单的字符串来响应:

PHP 代码

// if a file was posted
if($_FILES && $_POST){

if(move_uploaded_file($file, $dir)) {
echo "File successfully sent to server.";
}

我可以用这段安静的代码得到这个文本答案:

Java 代码

HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

// get server response
if (resEntity != null) {
return EntityUtils.toString(resEntity).trim();
}

现在我不想得到一个简单的文本响应,但我希望得到一个完整的文件。我没有太多经验,卡住了:

PHP 代码

if(move_uploaded_file($app, $upload_file . $file_ending)) {
readfile($res_file); // read file and write it output buffer
}

Java 代码

HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

if (resEntity != null)
return String.valueOf(resEntity.getContentLength());

getContentLength 返回 14,这绝对不是以字节为单位的文件大小。

如何从 PHP 服务器获取文件作为响应?

最佳答案

您确定您发送的文件不是 14 字节的吗?检查您得到的响应是否不是错误声明。如果您收到合法响应,则 response.getEntity().getContentLength() 应显示 "the number of bytes of the content" .

至于 PHP 部分,这是其他人成功使用的部分:

if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}

参见 reference .

关于php - Android:通过 HttpResponse 从 PHP 服务器获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26279925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com