我尝试使用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);
}
}
答案 0 :(得分:2)
尝试更改此行:
$file = '/home/myhome/public_html/myfolder/' + $file_name;
为:
$file = '/home/myhome/public_html/myfolder/' . $file_name;
在PHP文件中。