一、下载图片到默认地址
①、请求后台
var curPath = window.document.location.href;
var pathName = window.document.location.pathname;
var pos = curPath.indexOf(pathName);
var localhostPaht = curPath.substring(0,pos);
var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
var baseuri = localhostPaht + projectName;
function onl oadurl(url){ var qrcode = baseuri + "/xxxxx/onloadurl?qrcodeUrl=" + url; var alink = document.createElement("a"); alink.href = qrcode; alink.download = new Date().getTime() + ".jpg"; alink.click(); }
②后台处理
/** * 下载图片信息 * @param request * @param response * @param id * @return * @throws IOException * @throws MalformedURLException */ @RequestMapping("/onloadurl") public void onl oadurl(HttpServletRequest req, HttpServletResponse response, String qrcodeUrl) throws MalformedURLException, IOException { HttpURLConnection connection = (HttpURLConnection) new URL(qrcodeUrl).openConnection(); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); if (inputStream != null) { BufferedImage bufferedImage = ImageIO.read(inputStream); ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); response.getOutputStream().close(); inputStream.close(); } } }