Is there any way to specify a suggested filename w

2018-12-31 05:30发布

If for example you follow the link:

data:application/octet-stream;base64,SGVsbG8=

The browser will prompt you to download a file consisting of the data held as base64 in the hyperlink itself. Is there any way of suggesting a default name in the markup? If not, is there a JavaScript solution?

16条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 06:07

The following Javascript snippet works in Chrome by using the new 'download' attribute of links and simulating a click.

function downloadWithName(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  link.click();
}

And the following example shows it's use:

downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")
查看更多
呛了眼睛熬了心
3楼-- · 2018-12-31 06:08

Chrome makes this very simple these days:

function saveContent(fileContents, fileName)
{
    var link = document.createElement('a');
    link.download = fileName;
    link.href = 'data:,' + fileContents;
    link.click();
}
查看更多
浪荡孟婆
4楼-- · 2018-12-31 06:09

Use the download attribute:

<a download='FileName' href='your_url'>

Live example on html5-demos.appspot.com/....

Currently works on Chrome, Firefox, Edge, Opera, and desktop Safari but not iOS Safari or IE11.

查看更多
步步皆殇っ
5楼-- · 2018-12-31 06:09

you can add a download attribute to the anchor element.

sample:

<a download="abcd.cer"
    href="data:application/stream;base64,MIIDhTC......">down</a>
查看更多
唯独是你
6楼-- · 2018-12-31 06:09

Using service workers, this is finally possible in the truest sense.

  1. Create a fake URL. For example /saveAs/myPrettyName.jpg
  2. Use URL in <a href, <img src, window.open( url ), absolutely anything that can be done with a "real" URL.
  3. Inside the worker, catch the fetch event, and respond with the correct data.

The browser will now suggest myPrettyName.jpg even if the user opens the file in a new tab, and tries to save it there. It will be exactly as if the file had come from the server.

// In the service worker
self.addEventListener( 'fetch', function(e)
{
    if( e.request.url.startsWith( '/blobUri/' ) )
    {
        // Logic to select correct dataUri, and return it as a Response
        e.respondWith( dataURLAsRequest );
    }
});
查看更多
公子世无双
7楼-- · 2018-12-31 06:12

Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.

var exportFileName = "export-" + filename;
$('<a></a>', {
    "download": exportFileName,
    "href": "data:," + JSON.stringify(exportData, null,5),
    "id": "exportDataID"
}).appendTo("body")[0].click().remove();
查看更多
登录 后发表回答