好的,所以我不知道你的平台,所以会给一个 ASP.NET 版本。如果您正在使用其他东西,那么我已经发表评论,因此您应该能够适应您的平台。
编辑:现在知道用户正在使用 PHP,因此为 PHP 添加了代码 sn-p(不强大,但我不是 PHP 开发人员)...
1) PHP/ASP 也一样 你得到一个浏览器不会自动显示的文件吗?即 .js 将按原样显示,但 exe 可能会触发文件下载对话框(如果有错误请有人纠正我,我会更新)
如果您的文件总是会是 .exe,那么您可能会侥幸逃脱:
$("body").append("<iframe src='http://www.targetsite.com/files/thefilename.exe'></iframe>");
但您更有可能使用参数来查找正确的文件(并隐藏直接下载
$("body").append("<iframe src='http://www.targetsite.com/downloader/?file=1234-1234-1234'></iframe>");
在某些 setTimeout 函数中。
如果文件类型未知,那么我建议将上述代码指向将文件字节流写入 http 响应的脚本文件(.ashx、php 等)。
对于 PHP:
<?php // Demo - send a (binary) file
$file = "ireland.jpg";//here you would use the query string parameter of the above
//ajax/iframe request eg file=1234-1234-1234 to find image in db
$fp = fopen($file,"r") ;
header("Content-Type: image/jpeg");//this would need to be modified to either show right content type or you could
//set it to Application/force-download
while (! feof($fp)) {
$buff = fread($fp,4096);
print $buff;
}
?>
警告请小心上面的代码。我突然想到你可能会直接传入文件名,我很确定有人可以使用它在你的应用程序的其他地方获取文件而无需仔细注意
对于 ASP:
我已经包含了一个示例 ashx(通用处理程序)解决方案:
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wardle.PdfGenerator;
using System.IO;
public partial class user_account_iframedownloader : System.Web.UI.Page
{
private IInformixRepository _rep;
//this page gets loaded into an iframe so we can do downloads while using ajax
protected void Page_Load(object sender, EventArgs e)
{
//write bytes out here i.e. see after for methods
}
}
示例字节输出方法(您只需要执行 File.getBytes 或其他操作 - 我的代码非常复杂,因此“为读者练习”
public static void PdfOutput(byte[] pdfData, string filename)
{
HttpContext.Current.Response.ContentType = "Application/pdf";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename);
HttpContext.Current.Response.BinaryWrite(pdfData);
}
public static void PdfZipOutput(byte[] zipData, string filename)
{
HttpContext.Current.Response.ContentType = "Application/zip";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename);
HttpContext.Current.Response.BinaryWrite(zipData);
}