js
//判断浏览器
function myBrowser() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isOpera = userAgent.indexOf("Opera") > -1;
if (isOpera) {
return "Opera"
};
if (userAgent.indexOf("Firefox") > -1) {
return "FF";
}if (userAgent.indexOf("Chrome") > -1) {
return "Chrome";
}
if (userAgent.indexOf("Safari") > -1) {
return "Safari";
}
if (userAgent.indexOf("compatible") > -1 &&
userAgent.indexOf("MSIE") > -1 && !isOpera) {
return "IE";
};
if (userAgent.indexOf("Trident") > -1) {
return "Edge";
}
}
//调用保存
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();
}
function oDownLoad(url) {
if (myBrowser() === "IE" || myBrowser() === "Edge") { //IE
odownLoad.href = "javascript:void(0)";
var oImg = document.createElement("img");
oImg.src = url;
oImg.id = "downImg";
var odown = document.getElementById("down");
odown.appendChild(oImg);
SaveAs5(document.getElementById('downImg').src)
} else { //!IE
odownLoad.href = url;
odownLoad.download = "";
}
}
var odownLoad = document.getElementById("imgdownload");
if(odownLoad!=undefined){
odownLoad.onclick = function () {
oDownLoad("/quality/estimate/manage/qr/download.jpg");
location.reload();
}
}
后台java
package com.by.hello;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class ImgDownload {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FileSystemView fsv = FileSystemView.getFileSystemView();
File com=fsv.getHomeDirectory(); //这便是读取桌面路径的方法了
//System.out.println(com.getPath());
download("http://avatar.csdn.net/1/3/B/1_li1325169021.jpg",
"1_li1325169021.jpg",com.getPath());
System.out.println("程序结束");
}
public static void download(String urlString, String filename,
String savePath) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5*1000);
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File sf=new File(savePath);
if(!sf.exists()){
sf.mkdirs();
}
OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
}