我想创建一个downloadscript允许部队下载的JPG文件中。 这是我的PHP脚本:
i want to create a downloadscript which allows Force Download of JPGs. This is my php script:
<?php
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: image/jpg");
header('Content-Disposition: attachment; filename="'.basename($GET['a']).'"');
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize(($GET['a']));
readfile(($GET['a']);
?>
这是我的js code一code段:
This is a code segment of my js code:
function downloadFile(a){
document.location = "download.php?a="+ a;
}
通过这个code样品没有任何反应。如果我追加的结果成HTML的标记时,它示出了该文件的内容。
With this code sample nothing happens. If i append the result into a HTML-tag, it shows the content of the file.
任何想法如何教浏览器下载这个文件?
Any ideas how to teach the browser to download this file?
编辑:SCRIPT更新
您无法下载文件,使用Ajax。所以,如果你有什么事情要发生在阿贾克斯,你应该回应返回URL,并将其应用于像 document.location =URL
来开始下载过程。
You can't download files with ajax. So, if you have something that should happen on ajax, you should return url in response and apply it like document.location = "url"
to start download process.
这里的一个音符。我记得,浏览器会阻止文件下载,如果它是由用户点击启动不。所以,这将正常工作:
One note here. As I remember, browser will block file download if it is initiated not by user click. So, this will work fine:
.click(function(){
document.location = "download url"
})
但是,如果它是由用户点击启动不是,它将被阻止。因此,code是这样的:
But if it is started not by user click, it will be blocked. So, code like this:
.click(function(){
$.ajax({...,
success:function(download_url_from_server){
document.location = download_url_from_server;
}});
})
将由浏览器被阻塞。所以,如果你想通过一些数据后,您可以提交一个表单到隐藏的iframe或使用空白页&LT;形式的目标=...
:
function checkToken(token){
var $form = $("#downloadForm");
if ($form.length == 0) {
$form = $("<form>").attr({ "target": "_blank", "id": "downloadForm", "method": "POST", "action": "script.php" }).hide();
$("body").append($form);
}
$form.find("input").remove();
var args = { a: "checkToken", b: token }
for (var field in args) {
$form.append($("<input>").attr({"value":args[field], "name":field}));
}
$form.submit();
}
而在script.php的,你需要从的download.php立即执行code,如果令牌是好,还是做一个重定向到下载脚本:
And in script.php you need to execute code from download.php immediately, if token is Ok, or do a redirect to download script:
header("Location: download.php?a=" . $filename)