1. 程式人生 > >servlet 動態生成zip檔案並下載

servlet 動態生成zip檔案並下載

@SuppressWarnings("unchecked")
	public void downloadZip(String batchSendTaskId, OutputStream os) {
		ZipOutputStream zos = null;
		try {
			zos = new ZipOutputStream(os);
			//設定編碼,防止檔名亂碼
			zos.setEncoding("GBK");

			//目標集合
			List<String> targetList = this.baseDao.getSession().createQuery(
					"select ct.target from ConvertTask ct where ct.taskState = ? and ct.batchSendTask.id = ?")
					.setString(0, TaskState.CONVERT_COMPLATED).setString(1, batchSendTaskId).list();

			for (String target : targetList) {
				ConvertTask convertTask = (ConvertTask) this.baseDao.getSession().createQuery(
						"from ConvertTask ct where ct.target = ? and ct.batchSendTask.id = ?").setString(0, target)
						.setString(1, batchSendTaskId).uniqueResult();

				Attachment attachment = convertTask.getAttachment();
				InputStream is = null;
				try {
					String attachmentName = attachment.getName();
					StringBuffer sb = new StringBuffer(attachmentName);
					sb.insert(attachmentName.lastIndexOf("."), "[" + convertTask.getTarget() + "]");
					ZipEntry zipEntry = new ZipEntry(sb.toString());
					zos.putNextEntry(zipEntry);

					is = new ByteArrayInputStream(attachment.getContent());
					byte[] buffer = new byte[256];
					int len = 0;

					while (-1 != (len = is.read(buffer, 0, 256))) {
						zos.write(buffer, 0, len);
					}
				} catch (IOException e) {
					throw new RuntimeException(e);
				} finally {
					if (is != null) {
						try {
							is.close();
						} catch (IOException e) {
							throw new RuntimeException(e);
						}
					}
					this.baseDao.getSession().flush();
					this.baseDao.getSession().clear();
				}
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (zos != null) {
				try {
					zos.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			try {
				os.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}

	}

使用ant.jar的ZipOutputStream和ZipEntry,不要使用java.util包中的(會有檔名亂碼)。
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;