java下载图片和在线预览图片

@RequestMapping(value = "/downloadFile",method = RequestMethod.GET)
public void downLoad(HttpServletRequest request,HttpServletResponse response) throws Exception {

    Logger log = LoggerFactory.getLogger(DownLoadDZZS.class);

    ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    String filePath = request.getParameter("path");
    String isOnLine = request.getParameter("isOnLine");

    log.info("下载预览参数========"+filePath+isOnLine);

    impl.download(filePath,isOnLine,request,response);

}

 

 

 

service层:

public void download(String path, String isOnLine, HttpServletRequest request, HttpServletResponse response) throws Exception {

    //判断身份证号是否为空
    if (path == null || path.equals("")) {
        ArrayList<Object> objects = new ArrayList<>();
        //   return new ResultEntity(1,"查询失败,身份证号不能为空",objects);
        return;
    }
    判断不动产证号是否为空
    if (isOnLine == null || isOnLine.equals("")) {
        ArrayList<Object> objects = new ArrayList<>();
        //  return new ResultEntity(1,"查询失败,不动产证号不能为空",objects);
        return;
    }
    File f = new File(path);
    if (!f.exists()) {
        response.sendError(404, "File not found!");
        return;
    }
    String fileName = f.getName();
    //fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

    BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
    byte[] buf = new byte[1024];
    int len = 0;
    response.reset(); // 非常重要
    if (isOnLine.equalsIgnoreCase("true")) { // 在线打开方式
        URL u = new URL("file:///" + path);
        response.setContentType(u.openConnection().getContentType());
        response.addHeader("Access-Control-Allow-Origin", "*");//解决跨域
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 文件名应该编码成UTF-8
    } else if (isOnLine.equalsIgnoreCase("false")) { // 纯下载方式
        response.setContentType("application/x-msdownload");
        response.addHeader("Access-Control-Allow-Origin", "*");//解决跨域
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
    } else {
        return;
    }
    OutputStream out = response.getOutputStream();
    while ((len = br.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    br.close();
    out.close();
}

 

 

请求事例:http://127.0.0.1:8183/downloadFile?path=F:/aaaa/aa.jpg&isOnLine=false

isOnLine=false控制是下载还是在线预览

 


版权声明:本文为Jzq0006原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。