application/force-download 不生效

时间:2019-03-19 12:14:27   收藏:0   阅读:3455
不管用什么方式都无法下载txt 设置application/force-download也不生效  很无奈
胡搞瞎搞  最终解决方案:但是没搞明白什么原理 问题解决
@RequestMapping(value = "/weChatDown/{fileId}")
public ResponseEntity<byte[]> weChatFiledownload(@PathVariable("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) throws Exception {
    DsCmsFile dsCmsFile = fileService.get(fileId);
    if (dsCmsFile != null) {
        String filePath = dsCmsFile.getFileUrl();
        String fileName = dsCmsFile.getFileName();
        File file = new File(filePath);
        long size = file.length();
        //为了解决中文名称乱码问题 这里是设置文件下载后的名称
        fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        response.reset();
        response.setHeader("Accept-Ranges", "bytes");
        //设置文件下载是以附件的形式下载
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
        response.addHeader("Content-Length", String.valueOf(size));

        ServletOutputStream sos = response.getOutputStream();
        FileInputStream in = new FileInputStream(file);
        BufferedOutputStream outputStream = new BufferedOutputStream(sos);
        byte[] b = new byte[1024];
        int i = 0;
        while ((i = in.read(b)) > 0) {
            outputStream.write(b, 0, i);
        }
        outputStream.flush();
        sos.close();
        outputStream.close();
        in.close();
    }
    return new ResponseEntity<>(HttpStatus.OK);

}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!