预览文件

本文发布于 2023年11月17日,阅读 49 次,点赞 3 次,归类于 微码

预览文件

@RequestMapping(value = "/preview", method = RequestMethod.GET)
    public void preview(String fileUrl,
                        String fileName,
                        HttpServletResponse response) {
        InputStream inputStream = null;
        try {
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            URL url = new URL(fileUrl);
            String contentType = URLConnection.guessContentTypeFromName(url.getFile());
            inputStream = url.openStream();
            // 设置响应头信息
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "inline; filename*=UTF-8''" + encodedFileName);
            response.setBufferSize(1024 * 1024);
            // 将文件内容写入响应输出流中
            IOUtils.copyLarge(inputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("preview file error.", e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("preview file inputStream close error.", e);
            }
        }

    }
本篇完