简体   繁体   English

如何使用Java脚本下载.text文件

[英]How Download .text files using java script

I download the file using script function, using iframe load and new page load. 我使用脚本功能,iframe加载和新页面加载来下载文件。

Using this method i download the all format file , but i can't able to download .txt file 使用这种方法,我下载了所有格式的文件,但无法下载.txt文件

Please help me to download file 请帮我下载文件

if(split[length-1]!="JPEG" && split[length-1]!="bmp" && split[length-1]!="pdf" && split[length-1]!="JPG" && split[length-1]!="jpg" && split[length-1]!="jpeg" && split[length-1]!="png" && split[length-1]!="gif") {
    $("body").append("<iframe src='" + file_path + "' style='display: none;' ></iframe>");
}
else {
    window.open(file_path);
}

Like Shadow Wizard said, this would work, if you were pointing the iframe to a url that sends back certain headers . 就像Shadow Wizard所说的那样,如果您将iframe指向发送回某些标头的url,那将起作用。 This is only possible with server side scripts, such as PHP: 这仅在服务器端脚本(例如PHP)中可行:

<?php
// download.php
if (!$_GET['url']) die();
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Stop accessing local file system.
$filename = pathinfo($url, PATHINFO_BASENAME);
$mime = mime_content_type($filename);

header('Content-disposition: attachment; filename=' . $filename);
header('Content-type: '. $mime);
echo file_get_contents($url);

Then you only need to edit your javascript to pass the url through this download.php file. 然后,您只需要编辑JavaScript即可通过此download.php文件传递网址。

if(split[length-1]!="JPEG" && split[length-1]!="bmp" && split[length-1]!="pdf" && split[length-1]!="JPG" && split[length-1]!="jpg" && split[length-1]!="jpeg" && split[length-1]!="png" && split[length-1]!="gif") {
    $("body").append("<iframe src='download.php?url=" + file_path + "' style='display: none;' ></iframe>");
}
else {
    window.open(file_path);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM