简体   繁体   中英

Creating a multi-line file and downloading with Chrome.downloads.download

I'm generating some content client side, and I want to download this generated content using chrome.downloads.download. Note that the download works fine, but somehow the downloaded file is not including the new lines (I'm adding the new lines using

lineContent += '\r\n';

This doesn't work. I've tried

'\r' or '\n'

as well, but no luck. Everything except the new line character is correct in the generated document. Any ideas why it might not be able to display the new lines?

I've already tried different editors so I doubt the editor is the reason why it's displaying all of it in a single line.

// when I'm debugging the fileData is showing as multi-lined, but after
// download, all of the content is a single line.
chrome.downloads.download({
            url: "data:text/plain," + fileData,
            filename: 'file.txt',
            conflictAction: "prompt",
            saveAs: true,
            }, function(downloadId) {
                console.log("Downloaded item with ID", downloadId);
        });

Use %0A (the url encoded entity of \\n ) to preserve it when downloading, either use it directly or pass your text to encodeURIComponent() to url encode the appropriate characters

 function download1(){ a = document.createElement("a") a.href = "data:text/plain,Stackoverflow%0ANewline"; a.download = "test.txt"; a.click(); } function download2(){ a = document.createElement("a") a.href = "data:text/plain,"+encodeURIComponent("Stackoverflow\\nNewline"); a.download = "test.txt"; a.click(); } 
 <button onclick="download1()">Download 1</button> <button onclick="download2()">Download 2</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM