调接口获取文件

  • 环境
  • 多个文件
    • 接口
    • 压缩工具类
  • 一个文件
    • 接口

环境

其他系统调接口获取一个或多个文件,但是按照平时写的一次只能传输一个文件,多个文件尝试也只能传输第一个,现找到一个方法,即使用压缩文件传输。

多个文件

接口

@RequestMapping(value = "/pickFile")
public String getPickFile(@RequestParam("type") String type, HttpServletRequest request, HttpServletResponse response) {
     
	String baseURL = "D:/pdf/pick/"; // 文件夹服务器上的地址
	List<String> fileNameList = xxxx.getPickFilename(type);
	if (null != fileNameList && fileNameList.size() > 0) {
     
		String zipName = type + "_pick.zip";
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
		// 下面两行支持跨域
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Method", "POST,GET");
		String fileURL = "";
		try {
     
			ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
			for (String fileName : fileNameList) {
     
				if (StringUtils.isNotBlank(fileName) && !StringUtils.equals("0", fileName)) {
     
					fileURL = baseURL + fileName;
					ZipUtils.doCompress(fileURL, out);
					response.flushBuffer();
				}
			}
			out.close();
		} catch (Exception e) {
     
			e.printStackTrace();
		}
	}
	return null;
}

压缩工具类

压缩使用主要包:
java.util.zip.ZipEntryjava.util.zip.ZipOutputStream

public class ZipUtils {
     

	private static Logger logger = LoggerFactory.getLogger(ZipUtils.class);

	private ZipUtils() {
     
	}

	/**
	 * 文件压缩
	 * 
	 * @param srcFile 目录或者单个文件地址
	 * @param zipFile 压缩后的ZIP文件地址
	 */
	public static void doCompress(String srcFile, String zipFile) throws IOException {
     
		doCompress(new File(srcFile), new File(zipFile));
	}

	/**
	 * 文件压缩
	 * 
	 * @param srcFile 目录或者单个文件
	 * @param zipFile 压缩后的ZIP文件
	 */
	public static void doCompress(File srcFile, File zipFile) throws IOException {
     
		ZipOutputStream out = null;
		try {
     
			out = new ZipOutputStream(new FileOutputStream(zipFile));
			doCompress(srcFile, out, "");
		} catch (Exception e) {
     
			throw e;
		} finally {
     
			out.close();// 记得关闭资源
		}
	}

	/**
	 * 文件压缩
	 * 
	 * @param filelName 目录或者单个文件地址
	 * @param out zip输出流
	 */
	public static void doCompress(String filelName, ZipOutputStream out) throws IOException {
     
		doCompress(new File(filelName), out, "");
	}

	/**
	 * 文件压缩
	 * 
	 * @param file 目录或者单个文件
	 * @param out zip输出流
	 */
	public static void doCompress(File file, ZipOutputStream out) throws IOException {
     
		doCompress(file, out, "");
	}
	/**
	 * 文件压缩
	 * 
	 * @param inFile 目录或者单个文件
	 * @param out zip输出流
	 * @param dir 目录路径
	 */
	public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
     
		if (inFile.isDirectory()) {
     
			File[] files = inFile.listFiles();
			if (files != null && files.length > 0) {
     
				for (File file : files) {
     
					String name = inFile.getName();
					if (!"".equals(dir)) {
     
						name = dir + "/" + name;
					}
					ZipUtils.doCompress(file, out, name);
				}
			}
		} else {
     
			ZipUtils.doZip(inFile, out, dir);
		}
	}

	public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
     
		String entryName = null;
		if (!"".equals(dir)) {
     
			entryName = dir + "/" + inFile.getName();
		} else {
     
			entryName = inFile.getName();
		}
		ZipEntry entry = new ZipEntry(entryName);
		out.putNextEntry(entry);

		int len = 0;
		byte[] buffer = new byte[1024];
		FileInputStream fis = new FileInputStream(inFile);
		while ((len = fis.read(buffer)) > 0) {
     
			out.write(buffer, 0, len);
			out.flush();
		}
		out.closeEntry();
		fis.close();
	}

	public static void doZip(InputStream in, ZipOutputStream out, String entryName) throws IOException {
     
		logger.info("---添加InputStream到压缩文件,InputStream大小:{}", in.available());
		ZipEntry entry = new ZipEntry(entryName);
		out.putNextEntry(entry);
		int len = 0;
		byte[] buffer = new byte[1024 * 5];
		while ((len = in.read(buffer)) > 0) {
     
			out.write(buffer, 0, len);
			out.flush();
		}
		out.closeEntry();
		in.close();
	}

	public static void main(String[] args) throws IOException {
     
		// doCompress("D:/testFiles", "D:/附件.zip");
	}
}

一个文件

接口

@RequestMapping(value = "/pickFile")
public String getReleaseFie(@RequestParam("type") String type, @RequestParam("no") String no,
		HttpServletRequest request, HttpServletResponse response) {
     
	try{
     
		PickFile file= xxx.getPick(no, type);
		if (null != file) {
     
			String fileName = file.getFileName();
			if (StringUtils.isNotBlank(fileName) && !StringUtils.equals("0", fileName)) {
     
				String baseURL = "http://ip:端口号/xxx/"; // 文件所放文件夹链接
				String fileURL = baseURL + fileName;
				BufferedInputStream bis = null;
				BufferedOutputStream bos = null;
	
				// 如果不存在乱码的情况可以忽略,由于请求参数文件名为中文,到后台会乱码,考虑操作系统和客户端浏览器默认编码
				// 判断服务器操作系统,本地开发使用windows
				String os = System.getProperty("os.name");
				if (os.toLowerCase().indexOf("windows") != -1) {
     
					fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
				} else {
     
					// 判断浏览器
					String userAgent = request.getHeader("User-Agent").toLowerCase();
					if (userAgent.indexOf("msie") > 0) {
     
						fileName = URLEncoder.encode(fileName, "ISO-8859-1");
					}
				}
				// 响应二进制流
				response.setContentType("application/octet-stream");
				response.reset();// 清除response中的缓存
				// 根据网络文件地址创建URL
				URL url = new URL(fileURL);
				// 获取此路径的连接
				URLConnection conn = url.openConnection();
				Long fileLength = conn.getContentLengthLong();// 获取文件大小
				// 设置reponse响应头,真实文件名重命名,就是在这里设置,设置编码
				response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
				response.setHeader("Content-Length", String.valueOf(fileLength));
	
				bis = new BufferedInputStream(conn.getInputStream());// 构造读取流
				bos = new BufferedOutputStream(response.getOutputStream());// 构造输出流
				byte[] buff = new byte[1024];
				int bytesRead;
				// 每次读取缓存大小的流,写到输出流
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
     
					bos.write(buff, 0, bytesRead);
				}
				response.flushBuffer();// 将所有的读取的流返回给客户端
	
				if (null != bis) {
     
					bis.close();
				}
				if (null != bos) {
     
					bos.close();
				}
			}
		}
	} catch (Exception e) {
     
		e.printStackTrace();
	}
	return null;
}

你可能感兴趣的:(文件,Java,java)