如何下载文件而不使用<a> element with download attribute or a server?

时间:2016-08-02 04:31:58

标签: javascript html5 file download fileapi

According to caniuse download元素的<a>属性受Microsoft Edge build 10547+支持,但{ {3}}

如何在不使用<a>属性集或服务器的download元素的情况下下载文件对象?

6 个答案:

答案 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的答案,但我想提供两种“黑客”方法:

  1. 如果文件非常小,您可以将ahref='data:[<mediatype>][;base64],<data>'一起使用。

    这可以允许您在mediatype中添加内容处置,模拟HTTP标头。这种黑客也不像人们希望的那样便携。

  2. 在中小型文件中,可以使用AJAX下载文件,然后use the Javascript File API to prompt for file saving(API不支持保存,但很容易将数据转换为数据URL)。

    如果您想避免使用Javascript文件API,可以尝试模拟锚点击,suggested here

  3. 再次,正如Leo Farmer所指出的,这些解决方案不能保证浏览器不会在新标签中打开文件而不是将其保存到磁盘,但我认为可以说所有用户都会能够优雅地降级为cmd+Sctrl+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-streamencodeURIComponent()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>

plnkr http://plnkr.co/edit/IS1OC0laRwL3BuuF9zay?p=preview

答案 4 :(得分:1)

  

使用FileSaver.js

它支持所有常用的浏览器。

只需包含:

<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中我们可以使用下面的代码

HTML

  @using (Html.BeginForm("GetAttachment", "User", FormMethod.Post))
                {

                    <button type="submit">Download</button>   
                }

MVC控制器

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);
}