According to caniuse download
元素的<a>
属性受Microsoft Edge build 10547+支持,但{ {3}}
如何在不使用<a>
属性集或服务器的download
元素的情况下下载文件对象?
答案 0 :(得分:13)
有许多方法可以触发下载。以下是一些:
使用表格:
<form method="get" action="mydoc.doc">
<button type="submit">Download</button>
</form>
使用javascript:
<button type="submit" onclick="window.open('mydoc.doc')">Download</button>
答案 1 :(得分:3)
虽然我支持@LeoFarmer的答案,但我想提供两种“黑客”方法:
如果文件非常小,您可以将a
与href='data:[<mediatype>][;base64],<data>'
一起使用。
这可以允许您在mediatype
中添加内容处置,模拟HTTP标头。这种黑客也不像人们希望的那样便携。
在中小型文件中,可以使用AJAX下载文件,然后use the Javascript File API to prompt for file saving(API不支持保存,但很容易将数据转换为数据URL)。
如果您想避免使用Javascript文件API,可以尝试模拟锚点击,suggested here。
再次,正如Leo Farmer所指出的,这些解决方案不能保证浏览器不会在新标签中打开文件而不是将其保存到磁盘,但我认为可以说所有用户都会能够优雅地降级为cmd+S
或ctrl+S
键盘快捷键: - )
答案 2 :(得分:2)
您可以使用download属性和jquery执行此操作。下载属性不支持ie和safari / ios。所以你可以使用jquery来做那个
$('.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>
答案 3 :(得分:1)
您可以使用手动创建的文件data URI
data:[<mediatype>][;base64],<data>
表示,也可以使用FileReader()
,.readAsDataURL()
,MIME
类型设置为application/octet-stream
,encodeURIComponent()
,window.open()
<script>
var file = "data:application/octet-stream,"
+ encodeURIComponent("<!DOCTYPE html>"
+ "<html><body>"
+ "<div>abc</div>"
+ "</body></html>");
var saveFile = window.open(file, "_self");
</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>
答案 4 :(得分:1)
它支持所有常用的浏览器。
只需包含:
<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中也能工作&lt; 6,Opera&lt; 15和FireFox&lt; 20你需要包含Blob.js作为依赖。
答案 5 :(得分:-1)
如果您正在使用服务器端,请按照表单提交机制呈现页面。 在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);
}