gpt4 book ai didi

java - 使用 PHP 下载特定文件

转载 作者:行者123 更新时间:2023-11-30 02:33:44 28 4
gpt4 key购买 nike

我尝试使用 PHP 下载特定文件,如果我指定如下代码:

<?php

$file = '/home/myhome/public_html/myfolder/940903105955.txt';

if (file_exists($file)) {

header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
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;
}

?>

它可以工作,但请注意文件名已指定。

但是,如果我这样做:

    <?php

$file_name = $_GET['file_name'];

$file = '/home/myhome/public_html/myfolder/' + $file_name;

if (file_exists($file)) {

header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
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;
}

?>

这不起作用,为什么会这样?

这是处理下载到我的电脑的 java 代码:

public static void saveFileFromUrlWithJavaIO(String fileName, String fileUrl)
throws MalformedURLException, IOException {

BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(fileUrl).openStream());
fout = new FileOutputStream(fileName);

byte data[] = new byte[1024];
int count;

while ((count = in.read(data, 0, 1024)) != -1) {

fout.write(data, 0, count);
System.out.print(data);
}

} finally {

if (in != null)
in.close();
if (fout != null)
fout.close();
}

这就是我调用该函数的方式:

private void btn_downloadActionPerformed(java.awt.event.ActionEvent evt) {                                             
// TODO add your handling code here:
String url = "http://myurl.com/download_resubmission_file.php?file_name="+ "940903105955.txt";

try {
saveFileFromUrlWithJavaIO(path_to_save_file, url);
} catch (IOException ex) {
Logger.getLogger(InsuranceMain.class.getName()).log(Level.SEVERE, null, ex);
}
}

最佳答案

尝试更改此行:

$file = '/home/myhome/public_html/myfolder/' + $file_name;

至:

$file = '/home/myhome/public_html/myfolder/' . $file_name;

在您的 PHP 文件中。

关于java - 使用 PHP 下载特定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43671502/

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