获取springboot项目根路径,读取根路径下的文件,并在浏览器访问时下载

需求:获取springboot项目根路径,读取根路径下的文件,并在浏览器访问时下载

思路:

太简单,直接上代码


@RequestMapping("/convert/down/furtherinvestigate/{Patient_id}")
@ResponseBody
public String DownloadfurtherinvestigateFile(@PathVariable int Patient_id,HttpServletResponse response) throws IOException {
    String jar_parent="";
    try {
        //获得项目根路径
        jar_parent = new File(ResourceUtils.getURL("classpath:").getPath()).getParentFile().getParentFile().getParent();
        jar_parent += File.separator+"HeadInjurySpringboot_local"+File.separator+"patient"+Patient_id+".xml";
        //System.out.println("文件路径"+jar_parent);
        File file = new File(jar_parent);
        String fileName = file.getName();
        //System.out.println("文件名称"+fileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStream fis = new BufferedInputStream(fileInputStream);
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();

        // 清空response
        response.reset();
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        //Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
        //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
        // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 告知浏览器文件的大小
        response.addHeader("Content-Length", "" + file.length());
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outputStream.write(buffer);
        outputStream.flush();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return "SUCCESS!";
}
posted @ 2022-05-05 18:46  李荣杰的博客  阅读(1253)  评论(0)    收藏  举报