1. 程式人生 > >Java 下載工具類(多檔案打包下載, 單檔案下載, 單檔案預覽)

Java 下載工具類(多檔案打包下載, 單檔案下載, 單檔案預覽)

1. 準備標準檔案類DocumentOModel

@Data
@ApiModel("文件資訊(轉換後)")
public class DocumentOModel {

    @ApiModelProperty(
            value = "文件ID",
            position = 1)
    private String documentId;

    @ApiModelProperty(
            value = "文件名稱",
            position = 2)
    private String name;

    @ApiModelProperty(
            value = "文件型別",
            position = 3)
    private String documentType;

    @ApiModelProperty(
            value = "文件內容",
            position = 4)
    private byte[] content;

2. 下載幫助類(重點)

/**
 * Description:下載預覽幫助類
 * <p>
 * 功能預覽:
 * 1.線上預覽pdf.....
 * 2.壓縮多個檔案成zip包,下載
 * 3.直接下載檔案
 * </p>
 * version: 1.0.1
 * User: zhouzhou
 * Date: 2018-10-30
 * Time: 14:08
 */
public class DownloadHelper {
    private static final Logger logger = LoggerFactory.getLogger(DownloadHelper.class);

    /**
     * 預覽pdf
     *
     * @param documentOModel 標準檔案類
     */
    public static void previewFile(DocumentOModel documentOModel) {
        try {
            // 進行預覽流
            HttpServletResponse httpServletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            httpServletResponse.setContentType("application/" + documentOModel.getDocumentType());
            OutputStream toClient = new BufferedOutputStream(httpServletResponse.getOutputStream());
            toClient.write(documentOModel.getContent());
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            logger.warn(String.format("預覽檔案{%s}發生異常{%s}", documentOModel.getName(), e.getMessage()), e);
            throw new RuntimeException(String.format("預覽檔案{%s}發生異常{%s}", documentOModel.getName(), e.getMessage()));
        }
    }

    /**
     * 壓縮檔案
     *
     * @param zipFileName     壓縮檔名
     * @param documentOModels 標準文件集合
     * @throws IOException 丟擲IO異常
     */
    public static void zipFile(String zipFileName, List<DocumentOModel> documentOModels) throws IOException {
        if (!CollectionUtils.isEmpty(documentOModels)) {
            HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpServletResponse httpServletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

            OutputStream outputStream = httpServletResponse.getOutputStream();

            //得請求頭中的User-Agent
            httpServletResponse.setContentType("application/zip");
            // 告訴客戶端該檔案不是直接解析,而是以附件形式開啟(下載)
            String characterEncoding = httpServletRequest.getCharacterEncoding();
            httpServletResponse.setHeader("Content-Disposition", "attachment"
                    + ";filename=" + URLEncoder.encode(zipFileName, characterEncoding)
                    + ";filename*=" + characterEncoding + "''" + URLEncoder.encode(zipFileName, characterEncoding));

            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
            // 打包中
            for (DocumentOModel documentOModel : documentOModels) {
                ZipEntry entry = new ZipEntry(documentOModel.getName());
                zipOutputStream.putNextEntry(entry);
                zipOutputStream.write(documentOModel.getContent());
                zipOutputStream.closeEntry();
            }

            zipOutputStream.flush();
            zipOutputStream.close();

            outputStream.flush();
            outputStream.close();
        }
    }

    /**
     * 下載指定單個檔案
     *
     * @param documentOModel 標準文件類
     */
    public static void downloadFile(DocumentOModel documentOModel) throws Exception {
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse httpServletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        OutputStream outputStream = httpServletResponse.getOutputStream();
        String type = documentOModel.getDocumentType();
        String fileName = documentOModel.getName();
        //得請求頭中的User-Agent
        httpServletResponse.setContentType("application/" + type);
        // 告訴客戶端該檔案不是直接解析,而是以附件形式開啟(下載)
        String characterEncoding = httpServletRequest.getCharacterEncoding();
        httpServletResponse.setHeader("Content-Disposition", "attachment"
                + ";filename=" + URLEncoder.encode(fileName, characterEncoding)
                + ";filename*=" + characterEncoding + "''" + URLEncoder.encode(fileName, characterEncoding));
        outputStream.write(documentOModel.getContent());

        // 關閉流
        outputStream.flush();
        outputStream.close();
    }

}

接下來就根據不同請求, 呼叫不同的方法吧, 希望能夠幫助到你