duadlkc5762218 2017-04-28 03:30
浏览 36

使用PHP下载特定文件

i am try to download a specific file using PHP, if i specify the code like so:

<?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;
}

?>

it works, however notice that the file name is specified.

However, if i do this:

    <?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;
    }

    ?>

it doesnt work, why is it so?

This is the java code to handle the download to my pc:

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();
}

This is how i call the function:

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);
    }
}  
  • 写回答

1条回答 默认 最新

  • dorkahemp972157683 2017-07-24 15:25
    关注

    Try to change this line:

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

    to:

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

    in your PHP file.

    评论

报告相同问题?