`
yugouai
  • 浏览: 492057 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

JSP下载文件

 
阅读更多

JSP下载远程服务器文件,通过数据流的方式获取。后台代码如下:

@RequestMapping
	public void requestDownlod(HttpServletResponse response, String filePath){
		RemoteDownLoadHelper helper = new RemoteDownLoadHelper();
		String resultFileAbsolutePath = helper.getTargetFilePath(filePath);
		List<File> fileList = FileUtil.listFiles(resultFileAbsolutePath);
		for (File file : fileList) {
			logger.info(file.getAbsolutePath());
		}
		File file = new File(resultFileAbsolutePath);
		InputStream inputStream = null;
		OutputStream outputStream = null;
		int BUFFER_SIZE = 1024;
		byte[] b = new byte[BUFFER_SIZE];
		int len = 0;
		try {
			inputStream = new FileInputStream(file);
			outputStream = response.getOutputStream();
			response.setContentType("application/force-download");
			String filename = file.getName();
//			filename = filename.substring(36, filename.length());
			response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));//中文编码问题处理
			response.setContentLength( (int) file.length( ) );  
            
            while((len = inputStream.read(b)) != -1){  
                outputStream.write(b, 0, len);  
            }  
		} catch (Exception e) {
		}finally{
			IOUtils.closeQuietly(inputStream);
			IOUtils.closeQuietly(outputStream);
			helper.deletePath(resultFileAbsolutePath);
		}
		 
	}

 RemoteDownLoadHelper类处理部分Controller的逻辑

public class RemoteDownLoadHelper {

	public String getTargetFilePath(String filePath){
		//第一步,将传入的filePath进行gz压缩
		String targetPath = new File(filePath).getParent();
		String resultFileAbsolutePath = CompressFileUtil.compressedFile(filePath, targetPath);
		return resultFileAbsolutePath;
	}
	
	public boolean deletePath(String filePath){
		return FileUtils.deleteQuietly(new File(filePath));
	}
	
}

 CompressFileUtil为压缩工具类,先压缩再传输下载

public class CompressFileUtil {

	/**
	 * @desc 将源文件/文件夹生成指定格式的压缩文件,格式zip
	 * @param resourePath 源文件/文件夹
	 * @param targetPath 目的压缩文件保存路径
	 * @return void
	 * @throws Exception
	 */
	public static String compressedFile(String resourcesPath, String targetPath) {
		File resourcesFile = new File(resourcesPath); // 源文件
		ZipOutputStream out = null;
		File targetFile = new File(targetPath); // 目的
		// 如果目的路径不存在,则新建
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}

		String targetName = resourcesFile.getName() + ".zip"; // 目的压缩文件名
		FileOutputStream outputStream;
		String targetAbsolutePath = targetPath + "/" + targetName;
		try {
			outputStream = new FileOutputStream(targetAbsolutePath);
			out = new ZipOutputStream(new BufferedOutputStream(outputStream));
			createCompressedFile(out, resourcesFile, "");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			IOUtils.closeQuietly(out);
		}
		return targetAbsolutePath;
	}

	/**
	 * @desc 生成压缩文件。 如果是文件夹,则使用递归,进行文件遍历、压缩 如果是文件,直接压缩
	 * @param out 输出流
	 * @param file 目标文件
	 * @return void
	 * @throws Exception
	 */
	private static void createCompressedFile(ZipOutputStream out, File file, String dir) {
		// 如果当前的是文件夹,则进行进一步处理
		FileInputStream fis = null;
		try {
			if (file.isDirectory()) {
				// 得到文件列表信息
				File[] files = file.listFiles();
				// 将文件夹添加到下一级打包目录
				out.putNextEntry(new ZipEntry(dir + "/"));

				dir = dir.length() == 0 ? "" : dir + "/";

				// 循环将文件夹中的文件打包
				for (int i = 0; i < files.length; i++) {
					createCompressedFile(out, files[i], dir + files[i].getName()); // 递归处理
				}
			} else { // 当前的是文件,打包处理
				// 文件输入流
				fis = new FileInputStream(file);

				out.putNextEntry(new ZipEntry(dir.equals("")?file.getName():dir));//兼容单独文件压缩时文件名为空字符串
				// 进行写操作
				int j = 0;
				byte[] buffer = new byte[1024];
				while ((j = fis.read(buffer)) > 0) {
					out.write(buffer, 0, j);
				}

			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭输入流
			IOUtils.closeQuietly(fis);
		}

	}

}

 

后台通过Reponse返回获取的数据流,在前端下载通过ajax+jquery下载

// Ajax 文件下载
	    jQuery.download = function (url, data, method) {
			// 获取url和data
			if (url && data) {
			    // data 是 string 或者 array/object
			    data = typeof data == 'string' ? data : jQuery.param(data);
			    // 把参数组装成 form的  input
			    var inputs = '';
			    jQuery.each(data.split('&'), function () {
					var pair = this.split('=');
					inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
			    });
			    // request发送请求
			    jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>')
					.appendTo('body').submit().remove();
			};
	    };

JQuery的ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以我们要实现ajax下载,不能够使用相应的ajax函数进行文件下载。但可以用js生成一个form,用这个form提交参数,并返回“流”类型的数据。

  调用:

jQuery.download('<%=request.getContextPath()%>/requestDownlod.do','filePath='+filePath,'post');

 

参考:

http://www.16kan.com/question/detail/293686.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics