天天看点

提供图片下载接口

1.浏览器请求地址:

localhost:8080/download/img?path=home/ccsp/img/abc.jpg

2.后台控制层

@Controller

@RequestMapping("download")

public class DownloadfilesController {

    @RequestMapping("/img")

    @ResponseBody

    public void init(HttpServletResponse response, @RequestParam("path")String path) {

        try {

            // 文件名

            String fileName=path.substring(path.lastIndexOf("/")+1);

            // 后缀名

            String fileSuffixName=   fileName.substring(fileName.lastIndexOf(".")+1);

            // 清除缓存

            response.reset();

            FileInputStream fileInputStream = new FileInputStream(path);

            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("application/" +fileSuffixName + ";" +"charset = UTF-8"); //设置字符集和文件后

            response.setHeader("Content-Disposition", "attachment;filename=" +fileName+"."+fileSuffixName);

            byte[] bytes = new byte[1024];

            while ((fileInputStream.read(bytes)) != -1) {

                outputStream.write(bytes);

            }

            fileInputStream.close();

            outputStream.flush();

            outputStream.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

3.取消登录URL拦截。

@WebFilter(filterName = "UrlFilter", urlPatterns = "/*", initParams = {@WebInitParam(name = "noFilterPath", value = "/download/img;...) })

继续阅读