How to download a file without using element w

2019-01-02 18:49发布

According to caniuse the download attribute of <a> element is supported at Microsoft Edge build 10547+, but not IE or Safari.

How to download a file object without using <a> element with download attribute set or a server?

6条回答
萌妹纸的霸气范
2楼-- · 2019-01-02 19:18

Use FileSaver.js

It supports all the commonly used browsers.

Just include:

<script type="text/javascript" src="FileSaver.min.js"></script>

and use it like:

var file = new File(["Hello, world!"], "hello world.txt", {type: "text/plain;charset=utf-8"});
saveAs(file);

Note: To make it work also in Safari < 6, Opera < 15 and FireFox < 20 you need to include Blob.js as a dependency.

查看更多
唯独是你
3楼-- · 2019-01-02 19:19

There are a number of ways of triggering a download. Following are a few:

Use a form:

<form method="get" action="mydoc.doc">
<button type="submit">Download</button>
</form>

Use javascript:

<button type="submit" onclick="window.open('mydoc.doc')">Download</button>
查看更多
呛了眼睛熬了心
4楼-- · 2019-01-02 19:20

You can use data URI data:[<mediatype>][;base64],<data> representation of file either created manually or utilizing FileReader(), .readAsDataURL(), with MIME type set to 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>

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

查看更多
牵手、夕阳
5楼-- · 2019-01-02 19:25

If you're using server-side then follow the form submission mechanism to render the page. In MVC we can use below code

Html

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

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

MVC Controller

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);
}
查看更多
若你有天会懂
6楼-- · 2019-01-02 19:34

Although I support @LeoFarmer's answer, I would like to offer two "hackable" approaches:

  1. If the file is very small, you can use a with the href='data:[<mediatype>][;base64],<data>'.

    This could allow you to add content disposition in the mediatype, emulating an HTTP header. This hack is also not as portable as one might hope.

  2. On small to medium files, it's possible to download the file using AJAX, and then use the Javascript File API to prompt for file saving (the API doesn't support saving, but it's easy to convert the data to a data URL).

    If you want to avoid the Javascript File API, you can try emulating an anchor click, as suggested here.

Again, as pointed out by Leo Farmer, these solutions can't promise that the browser won't open the file in a new tab instead of saving it to the disk, but I think it's safe to say that all users will be able to gracefully degrade to a cmd+S or ctrl+S keyboard shortcut :-)

查看更多
牵手、夕阳
7楼-- · 2019-01-02 19:36

You may do this using both download attribute and jquery. download attribute don't support in ie and safari/ios. So you may use jquery to do that

 $('.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>
查看更多
登录 后发表回答