让我详细讲解“Java实现服务器文件打包zip并下载的示例(边打包边下载)”的完整攻略。
1. 准备工作
在开始操作之前,需要准备以下两件事情:
- 相应的Java开发环境;
- 一个Web服务器,如Tomcat。
2. 解压文件并创建Java项目
首先,需要从服务器中解压需要打包的文件。接下来,在Java项目中创建以下文件夹:
src/main/java
src/main/webapp
src/main/resources
3. 添加依赖
在pom.xml文件中添加以下依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>
4. 创建Servlet
创建一个名为"DownloadServlet"的servlet,用来处理下载操作,代码如下:
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int BUFFER_SIZE = 4096;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//获取上传的文件
String zipFilePath = request.getParameter("zipFilePath");
File zipFile = new File(zipFilePath);
//设置响应的头文件信息
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFile.getName() + "\"");
response.setContentLength((int) zipFile.length());
//获取输出流
FileInputStream inputStream = new FileInputStream(zipFile);
OutputStream outputStream = response.getOutputStream();
//缓冲区
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
//写缓冲区数据到输出流
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
//关闭流
inputStream.close();
outputStream.close();
out.println("<div style='text-align:center;'>");
out.println("<br><br><br>");
out.println("<h1>文件下载成功!</h1>");
out.println("</div>");
}
}
5. 创建JSP页面
创建一个名为"index.jsp"的JSP页面,用来上传文件并下载打包后的文件,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文件上传和打包下载</title>
</head>
<body>
<form action="DownloadServlet" method="post" enctype="multipart/form-data">
<div>
请选择要上传的文件:<input type="file" name="file" /><br /><br />
<input type="submit" value="上传文件" /><br /><br />
<input type="hidden" name="zipFilePath" value="">
<% out.println("<br /><br />");
out.println("<a href=\"#\" onclick=\"zipDownload();\">下载Zip文件</a>");
out.println("<br /><br />"); %>
</div>
</form>
<script type="text/javascript">
function zipDownload() {
var zipFilePath = $('input[name=zipFilePath]').val();
if(zipFilePath.length <= 0) {
alert("请先上传文件!");
} else {
window.location.href = "DownloadServlet?zipFilePath=" + zipFilePath;
}
}
$('form').submit(function(){
$(this).ajaxSubmit({
success:function(data){
$('input[name=zipFilePath]').val(data);
alert("文件上传成功!");
},
error:function(){
alert("文件上传失败!");
},
url:'FileUploadServlet',
type:'POST',
dataType: 'text',
clearForm: true,
resetForm: true,
timeout: 60000
});
return false;
});
</script>
</body>
</html>
6. 创建上传文件的Servlet
创建一个名为"FileUploadServlet"的servlet,用来处理文件上传操作,代码如下:
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
@Override
public void init() throws ServletException {
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//获取上传的文件
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
FileItem fileItem = null;
String fileName = "", filePath = "";
while(fileItemsIterator.hasNext()) {
fileItem = (FileItem)fileItemsIterator.next();
if(!fileItem.isFormField()) {
fileName = fileItem.getName();
filePath = getServletContext().getRealPath("/WEB-INF/temp") + File.separator + fileName;
File uploadedFile = new File(filePath);
fileItem.write(uploadedFile);
out.println(filePath);
}
}
ZipOutputStream zipStream = null;
FileOutputStream outputStream = null;
try {
String zipFilePath = getServletContext().getRealPath("/WEB-INF/temp") + File.separator + "download.zip";
outputStream = new FileOutputStream(zipFilePath);
zipStream = new ZipOutputStream(new BufferedOutputStream(outputStream, BUFFER_SIZE));
File file = new File(filePath);
addToZipFile(file, zipStream);
zipStream.flush();
zipStream.close();
out.println(zipFilePath);
} catch (Exception ex) {
out.println(ex.getMessage());
}
} catch (FileUploadException ex) {
out.println(ex.getMessage());
} catch (Exception ex) {
out.println(ex.getMessage());
}
}
private static final int BUFFER_SIZE = 4096;
/**
* 将文件放入压缩包中
* @param file
* @param zipStream
* @throws FileNotFoundException
* @throws IOException
*/
private static void addToZipFile(File file, ZipOutputStream zipStream) throws FileNotFoundException, IOException {
FileInputStream inputStream = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zipStream.putNextEntry(zipEntry);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
zipStream.write(buffer, 0, bytesRead);
}
inputStream.close();
zipStream.closeEntry();
}
}
7. 测试
打开浏览器并输入服务器地址,即可访问上传文件和下载打包后文件的功能。
示例一:
上传一个文件后,打包下载该文件。
示例二:
上传多个文件后,打包下载这些文件。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java实现服务器文件打包zip并下载的示例(边打包边下载) - Python技术站