emanjusaka —— 彼岸花开可奈何

彼岸花开可奈何

预览文件

29
2023-11-17

预览文件

@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);
            }
        }

    }