The Java ftp compressed file is packaged into zip and downloaded to the local user through the browser download function

Keywords: Programming Java Apache ftp Spring

1. Import jar dependency package:

ant-1.9.7.jar

commons-net-3.3.jar

Baidu online: https://pan.baidu.com/s/1u7m5NYans-UK_h8VSEPfbA

Extraction code: qy12

2. Create a tool class DownloadFileUtil.java and write the following code:

package com.zghky.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class DownloadFileUtil {

	/**
	 * Create a zip and download
	 * @param zipFileName Package name
	 * @param filePath Specific path splicing of files to be downloaded (;)
	 * @param request
	 * @param response
	 * @throws FTPConnectionClosedException
	 * @throws IOException
	 */
	public static void createAndDownloadZip(String zipFileName, String filePath, 
			HttpServletRequest request, HttpServletResponse response) 
					throws FTPConnectionClosedException, IOException, Exception {
		List<String> fileList = Arrays.asList(filePath.split(";"));
		ZipOutputStream zos = null;
		
		String savePath = "C:/test";// Compressed package storage path
		File dirFile = new File(savePath);
		if(!dirFile.exists()) {
			dirFile.mkdirs();
		}
		
		String zipPath = savePath + "/" + zipFileName + ".zip";
		zos = new ZipOutputStream(new FileOutputStream(zipPath));// Create a compressed package
		zos.setEncoding("UTF-8");
		toZip(fileList, zos);// Compress files
		// Close
		if(zos != null) {
			try {
				zos.flush();
				zos.close();
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
		downloadZip(zipPath, request, response);// Download compressed package
		// Delete compressed package (omitted)
		......
	}
	
	/**
	 * Compress files
	 * @param fileList Specific location of documents
	 * @param zos
	 * @throws IOException
	 */
	public static void toZip(List<String> fileList, ZipOutputStream zos) throws IOException {
		if(fileList != null && fileList.size() > 0) {
			for(String file : fileList) {
				// File read to file stream
				URL url = new URL("file:///"+ file); / / add the file: / / identifier to indicate the local file
				URLConnection connection = url.openConnection();
				InputStream in = connection.getInputStream();
				
				// Compressed file name
				//  File.separatorChar = \
				String[] fileStr = file.split("C:/test/");
				String zipPath = fileStr[1].substring(0, fileStr[1].lastIndexOf("/") + 1);
				zos.putNextEntry(new ZipEntry(zipPath));// Create a folder in a compressed file
				zipPath += file.substring(file.lastIndexOf("/") + 1, file.length());
				zos.putNextEntry(new ZipEntry(zipPath));// Create a file in the corresponding location of the compressed file
				
				// Write files in stream to compressed package
				byte[] buffer = new byte[1024];
				int r = 0;
				while((r = in.read(buffer)) != -1) {
					zos.write(buffer, 0, r);
				}
				in.close();
				
				// Delete (omit)
				......
			}
		}
	}
	
	/**
	 * Download zip package to local
	 * @param zipPath Compressed package absolute path
	 * @param request
	 * @param response
	 * @throws FTPConnectionClosedException
	 * @throws IOException
	 */
	public static void downloadZip(String zipPath, 
			HttpServletRequest request, HttpServletResponse response) 
					throws FTPConnectionClosedException, IOException {
		// Get the file name to download
		String fileName = zipPath.substring(zipPath.lastIndexOf("/")+1, zipPath.length());
		// System.out.println("filename:" + fileName);
		response.reset();
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/octet-stream");
		// Set the content disposition response header to control the browser to open the file as a download
		response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "utf-8"));
		// Get file input stream
		InputStream in = new FileInputStream(zipPath);
		int len = 0;
		byte[] buffer = new byte[1024];
		OutputStream out = response.getOutputStream();
		while((len = in.read(buffer)) > 0) {
			//Output buffer data to client browser
			out.write(buffer, 0, len);
		}
		in.close();
	}
}

3. Write a method at the controller level (the project is spring MVC mode):

@Controller
@RequestMapping("test")


@ResponseBody
	@RequestMapping("/downloadFile")
	public void downloadFile(String ids,
			HttpServletRequest request, HttpServletResponse response) 
					throws FTPConnectionClosedException, IOException, Exception {
		......
		// Compress download file
		DownloadFileUtil.createAndDownloadZip(zipName, filePath, request, response);
	}

Note: (1) zipName: zip package name;

(2) filePath: to compress the address splicing of files (the splicing symbol is a semicolon in English;) [multiple file paths need splicing];

4. Front end js:

window.location.href = path + "test/downloadFile?ids="+ids;

Note: if you want to send it with ajax, the browser will not respond at all. Because the format returned by ajax is the format of characters, the browser above will respond.

Transfer gate:

Java generates PDF Online through wkhtmltopdf: https://my.oschina.net/u/3986411/blog/3291128

Posted by bdee1 on Tue, 21 Apr 2020 07:08:52 -0700