简体   繁体   English

在IE中“保存为”按钮,在客户端保存文件

[英]“Save as”-button in IE, save file on client side

Is there any way to make a button that generates a text/xml file, sets the content-type to application-download, adds an attachment etc on the client side? 有没有办法制作一个生成text / xml文件的按钮,将内容类型设置为应用程序下载,在客户端添加附件等? What i want is a "download"-button on my page that saves an xml-file. 我想要的是在我的页面上的“下载”按钮,它保存了一个xml文件。 This is how i do the same thing on serverside: 这就是我在服务器端做同样的事情:

response.StatusCode = 200;
        response.ContentEncoding = Encoding.UTF32;
        response.AddHeader("content-disposition", "attachment; filename=" + fileName);
        response.AddHeader("Content-Transfer-Encoding", "binary");
        response.AddHeader("Content-Length", response.ContentEncoding.GetByteCount(xmlString).ToString());
        response.ContentType = "application-download";
        response.Write(xmlString);    

If you mean to create the file in jQuery/Javascript and be able to save it to disk from the browser, the answer is plain NO. 如果你的意思是在jQuery / Javascript中创建文件并且能够从浏览器将其保存到磁盘,答案显然是否定的。 Javascript is not allowed (for security reasons) to save to disk, neither to make the browser throw a "Save as..." popup for something locally created. 不允许Javascript(出于安全原因)保存到磁盘,也不允许浏览器为本地创建的内容弹出“另存为...”弹出窗口。 You have an easier solution to your question. 您可以更轻松地解决问题。 In your example you are creating the xml file and sending it as an attachment from the server, why dont you just make a button to download the file created by the server? 在您的示例中,您正在创建xml文件并将其作为附件从服务器发送,为什么不只是按下按钮来下载服务器创建的文件? You can't do it by plain ajax, cause it can't trigger downloads in the browser, but you can use the old "iframe download trick" to launch the download in the same page. 你不能通过简单的ajax来做,因为它无法在浏览器中触发下载,但你可以使用旧的“iframe下载技巧”在同一页面中启动下载。

function download(url_to_your_creating_file_servlet){
iframe = document.createElement('iframe');  
iframe.style.visibility = 'hidden';
document.body.appendChild(iframe);
iframe.src = url_to_your_creating_file_servlet;
}

Or if you don't mind to open another window/tab (a bit uglier) this also works: 或者,如果你不介意打开另一个窗口/标签(有点丑陋),这也有效:

<a href="url_to_your_creating_file_servlet" target="blank"> Download </a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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