关于压缩包上传和下载示例代码

结合springmvc的压缩包上传与下载

压缩包上传

@ResponseBody
	@RequestMapping(value = "/import", method = RequestMethod.POST)
	public ModelAndView upload(
			@RequestParam(value = "file", required = true) MultipartFile file,
			HttpServletRequest request) throws Exception
			{
				//获取写入文件的路径
				String wirteurl = request.getSession().getServletContext()
						.getRealPath(File.separator)
						+ "sitestemplates" + File.separator + name + ".zip";

				String message = SaveFileFromInputStream(file.getBytes(), wirteurl);
			}
	/**
	 * 从流中往文件里写东西
	 * 
	 * @param stream
	 *            输入流
	 * @param filename
	 *            写的文件名
	 * @throws IOException
	 */
	public String SaveFileFromInputStream(byte[] bytes, String url)
			throws IOException {
		// 根路径及创建目录文件
		File file = new File(url);
		FileCopyUtils.copy(bytes, file);
		return "ture";

	}

解压压缩包到指定目录

@ResponseBody
	@RequestMapping(value = "/createpackage", method = RequestMethod.POST)
	public String createpackage(@RequestBody SitePackInfo sitePackInfo,
			HttpServletRequest request)
	{
			// 获取解压根目录
		String siteRootUrl = request.getSession().getServletContext()
				.getRealPath(File.separator)
				+ "sites" + File.separator + sitePackInfo.getAlias();

		String writeUrl = request.getSession().getServletContext()
				.getRealPath(File.separator)
				+ "sitestemplates"
				+ File.separator
				+ sitePackInfo.getName()
				+ ".zip";
		try {
			// 压缩后的文件名
			File zipFile = new File(writeUrl);
			FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
			// 过滤流,用于维护数据校验和
			CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
					new CRC32());
			ZipOutputStream out = new ZipOutputStream(cos);
			String basedir = "";
			compress(file, out, basedir, sitePackInfo.getAlias());
			out.close();
		} catch (Exception e) {
			return "false";
		}
	}
	private void compress(File file, ZipOutputStream out, String basedir,
			String alias) {
		/* 判断是目录还是文件 */
		if (file.isDirectory()) {
			log.info("压缩:" + basedir + file.getName());
			compressDirectory(file, out, basedir, alias);
		} else {
			log.info("压缩:" + basedir + file.getName());
			compressFile(file, out, basedir, alias);
		}
	}

	/** 压缩一个目录 */
	private void compressDirectory(File dir, ZipOutputStream out,
			String basedir, String alias) {
		if (!dir.exists())
			return;

		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			/* 递归 */
			compress(files[i], out, basedir + dir.getName() + "/", alias);
		}
	}

	/** 压缩一个文件 */
	private void compressFile(File file, ZipOutputStream out, String basedir,
			String alias) {
		if (!file.exists()) {
			return;
		}
		try {
			BufferedInputStream bis = new BufferedInputStream(
					new FileInputStream(file));
			if (basedir.startsWith(alias + "/")) {
				basedir = basedir.substring((alias + File.separator).length());
			}
			ZipEntry entry = new ZipEntry(basedir + file.getName());
			out.putNextEntry(entry);
			
			//设置输出编码格式
			out.setEncoding("UTF-8");
			int count;
			byte data[] = new byte[8096];
			while ((count = bis.read(data, 0, 8096)) != -1) {
				out.write(data, 0, count);
			}
			bis.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

压缩包下载
@RequestMapping(value="/fileDown",method=RequestMethod.POST)
	public ModelAndView download(@RequestParam Map<String, String> m,HttpServletRequest request, 
			HttpServletResponse response)throws IOException
	{
		try {
				
				//pathName+File.separator+downPath就是那个压缩包
				long fileLength=new File(pathName+File.separator+downPath).length();
				//获取文件名
				//response.setContentType("application/octet-stream");//
				//加上URLEncoder.encode是防止传输的文件名有乱码的情况出现
				response.setHeader("Content-disposition", "attachment;filename=" + 
							URLEncoder.encode(downPath,"utf-8")+"");
				response.setHeader("Content-length", String.valueOf(fileLength));
				bis=new BufferedInputStream(new FileInputStream(pathName+File.separator+downPath));
				bos = new BufferedOutputStream(response.getOutputStream());
				//分批传送
				byte[] buff=new byte[2048];
				int bytesRead;
				while(-1!=(bytesRead=bis.read(buff,0,buff.length))){
					bos.write(buff,0,bytesRead);
				}
				bos.flush();
				return null;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if(bis!=null){
					bis.close();
				} if(bos!=null){
					bos.close();
				} 
			}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值