如何用javascript实现右键的图片另存为功能

JavaScript024

如何用javascript实现右键的图片另存为功能,第1张

<script language="javascript">

function SaveAs(href,name)

{

var a = window.open(href)

a.document.execCommand('Saveas',true,name)

a.window.close()

return false

}

</script>

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312">

<title>实验</title>

</head>

<body>

<a href="1.jpg" onClick="return SaveAs(this.href,'1.jpg')">下载</a>

</body>

</html>

js没有操作本地文件的权限,可以借助.net,php等后端语言才行的,将图片提交之后,返回个下载地址,window.open就自动下载了。

但是图片可以是svg的话

function saveAs(Url,filename){

var blob=new Blob([''], {type:'application/octet-stream'})

var url = webkitURL.createObjectURL(blob)

var a = document.createElementNS(xhtml,'a')

a.href = Url

a.download = filename

var e = document.createEvent('MouseEvents')

e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)

a.dispatchEvent(e)

webkitURL.revokeObjectURL(url)

2. saveAs(data,"new.svg")

使用JS实现单击连接保存图片

2种形式都可以

第一种:

<script>

function SaveAs5(imgURL)

...{

var oPop = window.open(imgURL,"","width=1, height=1, top=5000, left=5000")

for( oPop.document.readyState != "complete" )

...{

if (oPop.document.readyState == "complete")break

}

oPop.document.execCommand("SaveAs")

oPop.close()

}

</script>

<img src="t_screenshot_17616.jpg" id="DemoImg" border="0" onclick="SaveAs5(this.src)">

第二种:

<script>

function SaveAs5(imgURL)

...{

var oPop = window.open(imgURL,"","width=1, height=1, top=5000, left=5000")

for( oPop.document.readyState != "complete" )

...{

if (oPop.document.readyState == "complete")break

}

oPop.document.execCommand("SaveAs")

oPop.close()

}

</script>

<img src="../t_screenshot_17616.jpg" id="DemoImg" border="0">

<a href="#" onclick="SaveAs5(document.getElementById('DemoImg').src)">点击这里下载图片 </a>