IDEA文件下载

1.在html中添加超链接 (要下载的文件是固定的)


2.创建FiledownController

@RestController
 public class FileDownloadController {

@RequestMapping("download")
 public ResponseEntity download(HttpServletRequest request, HttpServletResponse response,String filename) throws Exception{
   String path = request.getServletContext().getRealPath("/upload/");
   System.out.println("@@@"+path);
   File file = new File(path + File.separator + filename);
    System.out.println("###"+file);
    if(file.exists()){
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition","attachment:filename="+ URLEncoder.encode(filename,"UTF-8"));
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;   //输入流
        OutputStream os = null;        //输出流
        BufferedInputStream bis = null;  //缓冲流

        try {
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int i =  bis.read(buffer);
            while (i != -1){
                os.write(buffer);
                i = bis.read(buffer);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
             bis.close();
             fis.close();
        }catch (IOException e){
            e.printStackTrace();
        }

    }
        return  null;
 }

}

你可能感兴趣的:(IDEA文件下载)