我一直在这里使用一些Javascript代码用于另一个线程(我找不到链接但会尽快添加。)
目标:创建一个按钮,允许用户在单击时单击而不是右键单击并另存为。在Chrome / Firefox中,您可以使用'下载'属性,但IE不支持此,客户端使用IE。
代码选择图像(当我运行代码时它可以看到大小)但是没有下载它并且错误出现为" 0"这没有用。我不是Javascript专家,所以任何帮助表示赞赏。我此时正在桌面上运行它。
代码:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function DownloadImage(imageURL) {
var oImage = document.getElementById(imageURL);
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
if (typeof canvas.getContext == "undefined" || !canvas.getContext) {
alert("browser does not support this action, sorry");
return false;
}
try {
var context = canvas.getContext("2d");
var width = oImage.width;
var height = oImage.height;
canvas.width = width;
canvas.height = height;
canvas.style.width = width + "px";
canvas.style.height = height + "px";
context.drawImage(oImage, 0, 0, width, height);
var rawImageData = canvas.toDataURL("image/png;base64");
rawImageData = rawImageData.replace("image/png", "image/octet-stream");
document.location.href = rawImageData;
document.body.removeChild(canvas);
}
catch (err) {
document.body.removeChild(canvas);
alert("Sorry, can't download" & canvas);
}
return true;
}
window.onload = function () {
var arrButtons = document.getElementsByTagName("button");
for (var i = 0; i < arrButtons.length; i++) {
var oButton = arrButtons[i];
var sRelatedImage = oButton.getAttribute("rel");
if (sRelatedImage && sRelatedImage.length > 0) {
oButton.onclick = function () {
HandleRelatedImage(this, sRelatedImage);
}
}
}
};
function HandleRelatedImage(oButton, sRelatedImage) {
var oImage = document.getElementById(sRelatedImage);
if (!oImage) {
alert("related image '" + sRelatedImage + "' does not exist");
return false;
}
return DownloadImage(sRelatedImage);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnDownload" rel="myimage" runat="server" Text="Button" />
<%-- <buttontype="btnDownload" rel="myimage">--%>
<asp:Image ID="myimage" runat="server" src="test.jpg" />
</div>
</form>
</body>
</html>
答案 0 :(得分:0)
我认为实现目标的最佳方法是通过设置返回页面的标题来实现服务器端。 (如果你因为某些原因需要在JS中执行它,可能不合适,但几年后我做了类似的事情,并且一些服务器端代码使事情变得更容易了。)
您似乎在使用VB,请尝试使用此链接http://www.dailycoding.com/Posts/how_to_force_a_file_to_download_in_aspnet.aspx