其他分享
首页 > 其他分享> > 下载图片

下载图片

作者:互联网

一、下载图片到默认地址

①、请求后台


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();
            }
        }
        
    }

 

标签:alink,inputStream,connection,pathName,var,response,下载,图片
来源: https://www.cnblogs.com/ki16/p/14872765.html