天天看點

提供圖檔下載下傳接口

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

繼續閱讀