java将文件添加到压缩包

发布时间:2024年01月17日
package com.ht.yhy.common.service;

import com.ht.dp.doc.business.FileDownloader;
import com.ht.dp.doc.command.dao.PrjFileDao;
import com.ht.dp.doc.command.service.TransferFileService;
import com.ht.dp.doc.constant.UploadTypeEnum;
import com.ht.dp.doc.query.vo.PrjFileVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
@Slf4j
public class ZipDownloaderService {

	@Resource
	private PrjFileDao prjFileDao;

	@Resource
	private TransferFileService transferfileservice;

	@Resource
	private FileDownloader fileDownloader;

	@Value("${fileZipPath:/data/nfs/files/word/}")
	private String fileZipPath;

	/**
	 * 将文件下载成zip
	 *
	 * @param fileIds
	 * @param zipName
	 * @param prjId
	 * @return
	 */
	public String downloadFileToZip(List<String> fileIds, String zipName, String prjId) {
		String storagePath = transferfileservice.getStoragePath(prjId, UploadTypeEnum.COMPLETE.getCode());
		String zipPath = fileZipPath + zipName;
		try (FileOutputStream baseStream = new FileOutputStream(zipPath);
			 ZipOutputStream zipStream = new ZipOutputStream(baseStream)) {
			for (String fileId : fileIds) {
				PrjFileVo byFileId = prjFileDao.getByFileId(fileId);
				if (byFileId == null) {
					log.info("文件id:{}不不存在", fileId);
					continue;
				}
				File file = getFile(byFileId.getFileMd5(), storagePath);
				addToZip(file, zipStream, byFileId.getFileName());
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("exception:{}", e.getMessage());
			log.error("压缩文件异常:{}", zipName);
		}
		return zipPath;
	}

	/**
	 * 文件返回给前端
	 *
	 * @param fileName
	 * @param request
	 * @param response
	 * @param file
	 */
	public void sendFileToResponse(String fileName, HttpServletRequest request, HttpServletResponse response, File file) {
		response.setContentType(request.getServletContext().getMimeType(fileName));
		response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"");
		try (InputStream fileStream = Files.newInputStream(file.toPath())) {
			IOUtils.copy(fileStream, response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
			log.info("exception:{}", e.getMessage());
			log.error("下载压缩包失败:{}", fileName);
			response.setStatus(500);
		}
	}


	private File getFile(String fileMd5, String storagePath) {
		File file = fileDownloader.downloadFile(fileMd5, storagePath);
		if (!file.exists()) {
			file = fileDownloader.downloadFile(StringUtils.upperCase(fileMd5), storagePath);
		}
		return file;
	}

	/**
	 * 将文件添加到压缩包
	 *
	 * @param file
	 * @param zos
	 * @param fileName
	 * @throws IOException
	 */
	private void addToZip(File file, ZipOutputStream zos, String fileName) throws IOException {
		zos.putNextEntry(new ZipEntry(fileName));
		try (FileInputStream fis = new FileInputStream(file);
			 ReadableByteChannel inputChannel = Channels.newChannel(fis)) {
			WritableByteChannel outputChannel = Channels.newChannel(zos);
			ByteBuffer buffer = ByteBuffer.allocateDirect(16384);
			while (inputChannel.read(buffer) != -1) {
				buffer.flip();
				outputChannel.write(buffer);
				buffer.clear();
			}
			zos.closeEntry();
		}
	}
}

文章来源:https://blog.csdn.net/qq_44198436/article/details/135659485
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。