gpt4 book ai didi

javascript - 如何从 IE 9 及更高版本强制下载 jsp 中的 html/javascript?

转载 作者:行者123 更新时间:2023-11-28 07:56:30 24 4
gpt4 key购买 nike

我有一个图片链接

<a href="relative_Path_of_IMG">Save</a>

我需要这个链接直接下载这个文件。在 Chrome 和 Firefox 上,使用“下载”属性可以正常工作

<a href="relative_Path_of_IMG" download>Save</a>

但是在 ie 上这不能正常工作。我在互联网上找到了 JS comand window.document.execCommand 并且我尝试以这种方式使用

window.document.execCommand('SaveAs', true, fileName || fileURL)

但是这种方式会打开一个窗口,让用户选择要保存的文件夹,并且我需要在用户下载的默认文件夹上自动执行下载,就像 Chrome 和 Firefox 上的属性下载一样。

谢谢

保罗·菲利普

最佳答案

您可以创建 JSP 并将其用作 servlet。它将通过参数收到一个链接,其中包含您要下载的图像的 URL。

此 servlet 将打开一个流来读取文件,并打开另一个流来将输出写入浏览器。这样您的浏览器将负责处理您的文件。

遵循此 JSP 的示例。

<%@ page language="java" contentType="image/jpeg; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String urlPrefix = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();

String fileUrl = request.getParameter("fileUrl");
if (fileUrl == null || "".equals(fileUrl.trim())) {
throw new Exception("No image Found.");
}

String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);

response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName, "UTF-8"));

String fullEncodedUrl = urlPrefix + URIUtil.encodePath(fileUrl);

URL url = new URL(fullEncodedUrl);

URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();

BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int len;
byte[] buf = new byte[1024];
while ((len = stream.read(buf)) > 0) {
outs.write(buf, 0, len);
}
outs.close();
%>

关于javascript - 如何从 IE 9 及更高版本强制下载 jsp 中的 html/javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26017715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com