根据caniuse,
如何在没有使用设置了
<a>
元素的download
属性在Microsoft Edge build 10547+中得到支持,但是不支持IE或Safari浏览器。如何在没有使用设置了
download
属性的<a>
元素或服务器的情况下下载文件对象?<a>
元素的download
属性在Microsoft Edge build 10547+中得到支持,但是不支持IE或Safari浏览器。download
属性的<a>
元素或服务器的情况下下载文件对象?有几种方法可以触发下载。以下是其中之一:
使用表单:
<form method="get" action="mydoc.doc">
<button type="submit">Download</button>
</form>
使用JavaScript:
<button type="submit" onclick="window.open('mydoc.doc')">Download</button>
window.open("blob:xyz")
在2023年对我来说仍然运行良好。这是参考链接:https://developer.mozilla.org/en-US/docs/Web/API/Window/open - Justin如果文件非常小,则可以使用带有href='data:[<mediatype>][;base64],<data>'
的 a
标签。
这样可以在 mediatype
中添加内容并模拟 HTTP 头。这个黑客技术可能并不像人们所期望的那么通用。
对于小到中等大小的文件,可以使用 AJAX 下载文件,然后使用 Javascript 文件 API 提示用户保存文件(API 不支持保存,但很容易将数据转换为数据 URL)。
如果你想避免使用 Javascript 文件 API,可以尝试模拟锚点点击,就像这里建议的那样。
cmd+S
或 ctrl+S
键盘快捷键 :-)它支持所有常用的浏览器。
只需包含以下内容:
<script type="text/javascript" src="FileSaver.min.js"></script>
并且像这样使用:
var file = new File(["Hello, world!"], "hello world.txt", {type: "text/plain;charset=utf-8"});
saveAs(file);
注意: 为了使它在Safari < 6,Opera < 15和FireFox < 20中也能正常工作,您需要将Blob.js作为依赖项包含进来。
File
构造函数是否可用? - guest271314 $('.download').click(function(e) {
e.preventDefault(); //stop the browser from following
window.location.href = 'uploads/file.doc';
});
<a href="no-script.html" class="download">Download</a>
数据 URI
data:[<mediatype>][;base64],<data>
文件表示,无论是手动创建还是利用 FileReader()
、.readAsDataURL()
,并将 MIME
类型设置为 application/octet-stream
,使用 encodeURIComponent()
和 window.open()
。<script></script>
<script>
var blob = new Blob(["abc"], {type:"text/plain"});
var reader = new FileReader();
reader.addEventListener("load", function(e) {
// replace existing `MIME` type with `application/octet-stream`
var file = "data:application/octet-stream;"
+ e.target.result.split(/;/)[1];
var saveFile = window.open(file, "_self");
});
reader.readAsDataURL(blob)
</script>
可能是一个与编程有关的链接或代码片段。如果您正在使用服务器端,则请遵循表单提交机制来呈现页面。在MVC中,我们可以使用以下代码
@using (Html.BeginForm("GetAttachment", "User", FormMethod.Post))
{
<button type="submit">Download</button>
}
public ActionResult GetAttachment()
{
string filename = "File.pdf";
string filepath = AppDomain.CurrentDomain.BaseDirectory + "/Path/To/File/" + filename;
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
<form>
不需要被提交到服务器。问题的要求是不使用服务器。 - guest271314