如何在 PHP REST API 中返回文件或下载

3
我有一个 rest api,端点是 getfilestart.php,它的作用是使用 PDO 在数据库中搜索文件名。我该如何获取文件并将其作为文件返回或在 postman 或浏览器中自动下载?我尝试了几种方法,但无法获取到文件。目录位于 ../files/
这里是用于下载的函数。
    public function downloadFile($param){
        $base_url = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];
     
        $q = "SELECT * FROM data_file WHERE module_id = ". $param;
        $stmt = $this->conn->prepare($q);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $filename = $row['file_name'];
        $request_url = $base_url .'/mtc_project_server/files/'.$filename;
    }

如果我转储请求URL,它是http://localhost/mtc_project_server/files/mir4.PNG,这是实际文件。如何使用REST下载它? 我尝试使用cURL和file_get_contents,但仍然不起作用。 谢谢事先帮忙。

1
选项1. 响应文件URL(例如-作为JSON .downloadURL属性),并使用重定向到该URL。选项2. 使用PHP readfile()header()强制下载 - vee
哦,那么对于选项1,您的意思是我将返回一个URL?我认为选项2更好,您能给我举个例子吗,先生?@vee - draw134
使用 cURL 下载示例(https://dev59.com/o2w15IYBdhLWcg3wxugh)。 - vee
尝试使用curl,但我得到了文件名为“filestart”,大小为0字节的错误@vee。我使用了浏览器。 - draw134
1
强制下载代码已经在链接中了。https://dev59.com/Dmw05IYBdhLWcg3wZBAC - vee
1个回答

2
从您的下载文件URL $request_url开始。
这是服务器端的强制下载源代码。
// https://dev59.com/Dmw05IYBdhLWcg3wZBAC

header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($request_url) . ".jpg\""); 
readfile($request_url);
exit();// end process to prevent any problems.

这是客户端使用的源代码,可供下载。

$url = 'https://my-domain.tld/rest-api/path.php';// change this to your REST API URL.

// https://dev59.com/o2w15IYBdhLWcg3wxugh

$fileext = pathinfo($url, PATHINFO_EXTENSION);
echo $fileext;
set_time_limit(0);
// For save data to temp file.
$fp = fopen (__DIR__ . '/localfile.tmp', 'w+');

//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

// get curl response
$response = curl_exec($ch); 

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

fwrite($fp, $body);

curl_close($ch);
fclose($fp);

// rename temp file.
preg_match('/filename=[\'"]?([\w\d\.\-_]+)[\'"]?/i', $header, $matches);
var_dump($matches);
if (isset($matches[1]) && !is_file(__DIR__ . '/' . $matches[1])) {
    // if target rename file is not exists.
    rename(__DIR__ . '/localfile.tmp', __DIR__ . '/' . $matches[1]);
} else {
    // for debug
    echo 'something wrong!<br>';
    var_dump($matches);
    echo '<br>';
    echo 'File was downloaded into ' . __DIR__ . '/localfile.tmp';
    exit();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接