1. 程式人生 > 其它 >SpringBoot檔案下載

SpringBoot檔案下載

@Override
    public String downloadFile(HttpServletResponse response, String name) {

        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("utf-8"),"ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            String path = ResourceUtils.getURL("classpath:").getPath()+"static/upload";
            String realPath = path.replace('/', '\\').substring(1,path.length());
            FileInputStream fileInputStream = new FileInputStream(realPath+"\\"+ name);
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while((len = fileInputStream.read(buff)) != -1){
                outputStream.write(buff,0,len);
            }
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "success";
    }