您的位置:首页 > 编程语言 > Java开发

web版用户通过浏览器下载图片java后台代码

2014-11-17 19:07 435 查看
/**

     * web版用户通过浏览器下载图片

     */

    @RequestMapping(value = "webDownloadImg/{imgId}", method = RequestMethod.GET)

    public @ResponseBody

    void webDownloadImg(@PathVariable String imgId, HttpServletRequest request, HttpServletResponse response) throws Exception {

        /*

        Map<String, Object> map = super.getParamsMap(json);

        String imgpath = map.get("imgpath").toString();

        imgpath = imgpath.substring(1,imgpath.length());*/

        // 获取图片绝对路径

        String path = request.getSession().getServletContext().getRealPath("/");

        //获取图片的url

        PictureAblumImgDto pto = pictureAlbumService.getPictureUrl(imgId);

        if(pto != null){

            // 创建文件输入流

            FileInputStream is = null;

            // 响应输出流

            ServletOutputStream out = null;

            String imgpath = pto.getImageUrl();

            try {

                File file = new File(path + imgpath);

                imgpath = imgpath.substring(1,imgpath.length());

                response.setContentType("application/octet-stream");

                //设置头信息,内容处理的方式,attachment以附件的形式打开,就是进行下载,并设置下载文件的命名

                response.setHeader("Content-Disposition","attachment;filename="+file.getName());

                is = new FileInputStream(file);

                out = response.getOutputStream();

                // 创建缓冲区

                byte[] buffer = new byte[1024];

                int len = 0;

                while ((len = is.read(buffer)) != -1) {

                    out.write(buffer, 0, len);

                }

                is.close();

                out.flush();

                out.close();

            } catch (Exception e) {

                logger.error("ERROR:" + e);

            }finally{

                is.close();

                out.flush();

                out.close();

            }

        }
    }

//前台jquery请求方式

function reqByAjax(url, param, reqType, callback, isAsync) {

    if(iBrowser.android){//解决部分安卓手机获取localStorage失败问题。

        mylocalStorage = getStorage();//获取localStorage

    }

    //设置默认值

    isAsync = (typeof(isAsync)=="undefined"||isAsync==="")?true:isAsync;

    var iAjax = $.ajax({

        url: "/"+url,

        type: reqType,

        dataType:"json",      

        contentType:"application/json",

        async:isAsync,

        data:JSON.stringify(param),

        beforeSend: function(request) {

           request.setRequestHeader("ticket", mylocalStorage.getItem("ticket") ? mylocalStorage.getItem("ticket"):"1s");

           //判断设备系统类型

           //request.setRequestHeader("osType", mylocalStorage.getItem("osType") ? mylocalStorage.getItem("osType"): 0);

           if(iBrowser.android){

               request.setRequestHeader("osType", "1");

              }else if(iBrowser.ios || iBrowser.iPhone || iBrowser.iPad){

                  request.setRequestHeader("osType", "2");

              }

           //设置guid

           request.setRequestHeader("guid", mylocalStorage.getItem("guid") ? mylocalStorage.getItem("guid"): 0);

        },

        success: function(data,textStatus) {

            if(data) {

                //ticket已过期执行登陆

                if(data.errorCode == 10003){

                    doLogin(url, param, reqType, callback, isAsync);

                }else{

                    if(callback) {

                        callback(data);

                    }

                }

            }

        },

        error: function() { //abort会执行error方法

            alert("亲 网络不给力,再刷新一下呗:)");

        }

    });

    //设置请求超时提醒,时间默认为20秒

    setTimeout(function() {

        if(iAjax && iAjax.readyState && iAjax.readyState != 4) //还在请求状态时

        {

             iAjax.abort();

             alert("亲 网络不给力,再刷新一下呗:)");

        }

    }, 1000*parseInt(20));

}

//发送请求

$("#w_download_id").html('<a href="/cs/webDownloadImg/'+download_img_albumId+'" style="text-align:center;"><img src="../images/download.png" style="width:26px;margin-top:11px;" onmousedown="userDownloadPicture()"/></a>');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  浏览器下载图片