如何使用JavaScript在Html中指定下载位置(How to specify download location in Html using JavaScript)

HTML/CSS IT屋
百度翻译此文   有道翻译此文
问 题

is it possible to specify the download location for a file from a Html page using JavaScript?

the function I am currently using to down my file is provided below.

function saveTextAsFile()
{      
    var textToWrite = document.getElementById("inputTextToSave").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'xlsx'});
    var fileNameToSaveAs = "NAME.csv";
    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    window.URL = window.URL || window.webkitURL;
    downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}

Thanks for your help in advance.

解决方案

Whether the browser asks the user or not is down to the preferences in the browser.

You can't bypass those preference, otherwise it would violate user's security.

What you can do is make sure you're sending the browser as much information as possible to help it make for a good user experience. If you're not already doing so, be sure to include a Content-Disposition header in the response to the download request, including a filename field:

Content-Disposition: attachment; filename=test.csv

Also see these other stackoverflow questions:
  Specify default download folder - possibly with JavaScript?
  Set file download destination using ExtJs

本文地址:IT屋 » How to specify download location in Html using JavaScript

问 题

是否可以使用JavaScript从Html页面指定文件的下载位置?



下面提供了我目前用于下载文件的功能。

  function saveTextAsFile()
{
var textToWrite = document.getElementById(“inputTextToSave”)。value ;
var textFileAsBlob = new Blob([textToWrite],{type:'xlsx'});
var fileNameToSaveAs =“NAME.csv”;
var downloadLink = document.createElement(“a”);
downloadLink.download = fileNameToSaveAs;
window.URL = window.URL || window.webkitURL;
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display =“none”;
document.body.appendChild(downloadLink);
downloadLink.click();
}


感谢您的帮助。


解决方案

浏览器询问用户与否,取决于浏览器的偏好。

您无法绕过这些偏好,否则会违反用户的安全。

您可以做的是确保您向浏览器发送尽可能多的信息,以便为用户提供良好的用户体验。如果您还没有这样做,请务必在对下载请求的响应中包含一个Content-Disposition标头,包括一个文件名字段:

  Content-Disposition:附件; filename = test.csv 


另请参阅以下其他stackoverflow问题:

  指定默认的下载文件夹 - 可能与JavaScript?

  使用ExtJs设置文件下载目标


本文地址:IT屋 » 如何使用JavaScript在Html中指定下载位置

官方微信
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注
与百万开发者在一起