文件下载-SpringMVC中测试

直接修改文件路径就可以,其他都不需要修改,帮助类已经为大家写好,可直接使用

1、Scroller:

/**
	 * 下载文件
	 * @author liupeng
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/testFileDown")
	public String testFileDown(HttpServletRequest request,HttpServletResponse response)throws Exception{
		FileOperator.FileDownload("e:"+File.separator+"tt.pdf", response);
		return null;
	}

2、FileOperator:

package com.utcsoft.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.utcsoft.common.servlet.Log4jInitServlet;
public class FileOperator {
	private final static Log logger = LogFactory.getLog(FileOperator.class);

	public static String path = "c:";
	public static int count = 0;

	public FileOperator(){
		String tmp = getClass().getResource("/").getPath();
		System.out.println(tmp);
	}

	public static String getRootPath(){
		try{
			String proName = Log4jInitServlet.propertiesPath;
			String tmp = System.getProperty("user.dir");
			path = tmp.substring(0, tmp.lastIndexOf(File.separator) + 1) + "bid" + File.separator;

			/*String osName = System.getProperties().getProperty("os.name");
			if (osName.toLowerCase().indexOf("windows") == -1)
			{
				path = "/home/bid/";
			}*/
			InputStream in = new BufferedInputStream(new FileInputStream(proName));
			Properties p = new Properties();
			p.load(in);
			//p.containsKey("path.file")
			if(!p.getProperty("path.file").toString().trim().equals("")){
				path = p.getProperty("path.file");
			}
		}
		catch(Exception ex){
			logger.error("[FileOperator] - 获取文件存放路径出现异常 - " + ex.getMessage());
		}
		return path;
	}
	//传送文件流到服务端
	public static void FileUpload(String filePath, HttpServletRequest request)throws ServletException, IOException{
		OutputStream out = null;
		InputStream ins = null;
		try {
			ins = request.getInputStream();
			out = new FileOutputStream(filePath);

			byte[] fileData = new byte[1024];
			int readCount = 0 ;
			count = 0;

			while((readCount=ins.read(fileData,0,1024)) != -1){
				out.write(fileData,0,readCount);
				count += readCount;
			}
			out.flush();
			logger.info("[FileUpload] - read file size:"+count + "=======" + request.getClass() + ":" + filePath);
		}catch(Exception ex){
			ex.printStackTrace();
			logger.error("[FileUpload] - " + ex + "=======" + request.getClass());
		}finally {
			out.close();
			ins.close();
		}
	}

	//传送文件流到服务端
	public static String loadString(String path) throws IOException
	{
		StringBuffer buf = new StringBuffer();
		String line = null;
		java.io.File file = new java.io.File(path);
		java.io.InputStream in = null;
		java.io.OutputStream out = null;
		java.io.BufferedReader reader = null;
		try
		{
			//获取fileInputStream流;
			in = new java.io.FileInputStream(file);
			//获取bufferedReader流;
			reader = new java.io.BufferedReader(new java.io.InputStreamReader(
					in));
			//循环读取行,如果读取的行为null时,则退出循环;
			while ((line = reader.readLine()) != null)
			{
				buf.append(line).append("\n");
			}
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			reader.close();
			in.close();
		}
		return buf.toString();
	}
	//在线保存并写文件
	public static void ReadFile(String path1, String path2) throws IOException  {
		OutputStream out = new FileOutputStream(path2);
		try {
			// 创建文件流对象
			FileInputStream is = new FileInputStream(path1);

			// 设定读取的字节数
			int n = 512;
			byte buffer[] = new byte[n];
			int readCount = 0 ;
			count = 0;
			// 读取输入流
			while ((readCount=is.read(buffer, 0, n) )!= -1) {
				out.write(buffer,0,readCount);
				count += readCount;
			}
			out.flush();
			// 关闭输入流
			out.close();
			is.close();
		}
		catch (IOException ioe) {
		}
	}

	//传送文件流到客户端
	public static void FileDownload(String filePath, HttpServletResponse response)throws ServletException, IOException{
		if("".equals(filePath))
			return;
		OutputStream out = null;
		InputStream ins = null;
		try {
			String fileName = StringOperator.GetFileName(filePath);
			File file = new File(filePath);
			long fileLength = file.length();

			ins = new FileInputStream(filePath);
			out = response.getOutputStream();

			byte[] fileData = new byte[1024];
			int readCount = 0 ;
			count = 0;
			//response.setHeader("Content-Type", "application/octet-stream");
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName,"UTF-8"));
			response.setHeader("Content-Length", String.valueOf(fileLength));

			while((readCount=ins.read(fileData,0,1024)) != -1){
				out.write(fileData,0,readCount);
				count += readCount;
			}
			out.flush();
			response.flushBuffer();
			logger.info("[FileDownload] - write file size:"+count + "=======" + response.getClass() + ":" + filePath);
		}catch(Exception ex){
			ex.printStackTrace();
			logger.error("[FileDownload] -" + ex+ "=======" + response.getClass());
		}
		finally {
			out.close();
			ins.close();
		}
		//PrintWriter out1 = response.getWriter();
		//out.clear();
		//out = pageContext.pushBody();
	}

	//文件上传--测试通过
	public static boolean FileUploadEx(String filePath, String fileName, long fileSize, InputStream inputStream){
		boolean flag = false;

		try{
			//filePath = StringOperator.GetEncodeString(filePath);
			//fileName = StringOperator.GetEncodeString(fileName);
			logger.info("[FileUploadEx] - filePath="+filePath+" fileName="+fileName);

			InputStream in = inputStream;
			File filed = new File(filePath);
			if (!filed.exists()) {
				filed.mkdirs();
			}
			byte[] buffer = new byte[4096];
			File outFile = new File(filePath + File.separator + fileName);
			FileOutputStream bos = null;
			bos = new java.io.FileOutputStream(outFile);
			int read;
			long yx = 0;

			while ((read = in.read(buffer)) != -1) {
				yx = yx + read;
				bos.write(buffer, 0, read);
			}

			in.close();
			bos.flush();
			bos.close();
			logger.info("[FileUploadEx] - file size:{" + fileSize + "}, read:{" + yx + "}");
			flag = true;

		}catch(Exception ex){
			logger.error(ex);
		}
		return flag;
	}

	public static void writefile(String filepath) {
		File file = new File(path);    //要写入的文件
		BufferedWriter writer = null;
		try {
			if (!file.exists())
				file.createNewFile();

			writer = new BufferedWriter(new FileWriter(file));
			writer.write("111111111111111111111");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null)
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
	/**
	 *  根据路径删除指定的目录或文件,无论存在与否
	 *@param sPath  要删除的目录或文件
	 *@return 删除成功返回 true,否则返回 false。
	 */
	public static boolean DeleteFolder(String sPath) {
		boolean  flag = false;
		File  file = new File(sPath);
		// 判断目录或文件是否存在
		if (!file.exists()) {  // 不存在返回 false
			return flag;
		} else {
			return deleteDirectory(sPath);
		}
	}
	/**
	 * 删除单个文件
	 * @param   sPath    被删除文件的文件名
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile(String sPath) {
		boolean   flag = false;
		File  file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}
	/**
	 * 删除目录(文件夹)以及目录下的文件
	 * @param   sPath 被删除目录的文件路径
	 * @return  目录删除成功返回true,否则返回false
	 */
	public  static boolean deleteDirectory(String sPath) {
		//如果sPath不以文件分隔符结尾,自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		//如果dir对应的文件不存在,或者不是一个目录,则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		//删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			//删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag) break;
			} //删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag) break;
			}
		}
		if (!flag) return false;
		//删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}
	public static void main(String[] args) {
		path = "F:\\test";
		boolean result = FileOperator.DeleteFolder(path);
		System.out.println(result);  

	} 

	//可以先将选择的所有的文件生成一个zip文件,然后再下载,该zip文件,即可实现批量下载
	public  static void  ZipOutputStreamDemo(String zipsPath,String sourcefile) throws Exception  {
		byte[] buffer = new byte[1024];
		//生成的ZIP文件名为Demo.zip
		String strZipName = "C:Demo.zip";

		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName));

		//需要同时下载的两个文件result.txt ,source.txt

		File[] file1 = { new File("C:\\test.pdf"),new File("C:\\test11.pdf")};

		for(int i=0;i<file1.length;i++) {

			FileInputStream fis = new FileInputStream(file1[i]);

			out.putNextEntry(new ZipEntry(file1[i].getName()));

			int len;

			//读入需要下载的文件的内容,打包到zip文件

			while((len = fis.read(buffer))>0) {

				out.write(buffer,0,len);

			}

			out.closeEntry();

			fis.close();

		}

		out.close();

		System.out.println("生成Demo.zip成功");
	}
}
时间: 2024-07-31 07:39:10

文件下载-SpringMVC中测试的相关文章

文件下载-SpringMVC中測试

直接改动文件路径就能够.其它都不须要改动,帮助类已经为大家写好,可直接使用 1.Scroller: /** * 下载文件 * @author liupeng * @param request * @param response * @return * @throws Exception */ @RequestMapping(value="/testFileDown") public String testFileDown(HttpServletRequest request,HttpS

SpringMVC中的XXE漏洞测试

SpringMVC框架支持XML到Object的映射,内部是使用两个全局接口Marshaller和Unmarshaller,一种实现是使用Jaxb2Marshaller类进行实现,该类自然实现了两个全局接口,用来对XML和Object进行双向解析.并且XML文件可以是DOM文档.输入输出流或者SAX handler. SpringMVC流行使用注解来快速开发,其中JAXB注解可以对JavaBean中需要与XML进行转化的地方进行标注.比如,实现XML文件到User对象的映射,User对象中使用J

【SpringMVC学习07】SpringMVC中的统一异常处理

我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发.测试通过手段减少运行时异常的发生.在开发中,不管是dao层.service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护.这篇博文主要总结一下SpringMVC中如何统一处理异常. 1. 异常处理思路 首先来看一下在spr

SpringMVC中使用Interceptor拦截器

SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理.比如通过它来进行权限验证,或者是来判断用户是否登陆,或者是像12306 那样子判断当前时间是否是购票时间. 一.定义Interceptor实现类 SpringMVC 中的Interceptor 拦截请求是通过HandlerInterceptor 来实现的.在SpringMVC 中定义一个Interceptor 非常简单,主要有两种方式,第一种方式是要定义的Intercep

【SpringMVC学习11】SpringMVC中的拦截器

Springmvc的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理.本文主要总结一下springmvc中拦截器是如何定义的,以及测试拦截器的执行情况和使用方法. 1. springmvc拦截器的定义和配置 1.1 springmvc拦截器的定义 在springmvc中,定义拦截器要实现HandlerInterceptor接口,并实现该接口中提供的三个方法,如下: //测试拦截器1 public class HandlerInterceptor1 im

【SpringMVC学习03】SpringMVC中注解和非注解方式下的映射器和适配器总结

从上一篇的springmvc入门中已经看到,springmvc.xml中的配置了映射器和适配器,是使用非注解的方式来配置的,这是非注解方式的一种,这里再复习一下: 1. 非注解方式 1.1 处理器适配器 上一节中使用的处理器适配器是:org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.即: SimpleControllerHandlerAdapter适配器能执行实现了Controller接口的Handler,所以我

Springmvc中配置Quartz使用,实现任务实时调度。

菜鸡的自我修炼,第一次接触quartz,做个记录.-------jstarseven 最近在项目中,第一次在springmvc中配置实用quartz,深刻的感受到quartz带来的方便,顺手做个记录. 简单介绍: Quartz 是个开源的作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制.Quartz 允许开发人员根据时间间隔(或天)来调度作业.它实现了作业和触发器的多对多关系,还能把多个作业与不同的触发器关联.整合了 Quartz 的应用程序可以重用来自不同事件的作业,

SpringMVC中使用Interceptor+Cookie实现在一定天数之内自动登录

一 简介 本篇文章主要介绍:在SpringMVC中如何使用Interceptor+Cookie实现在一定天数之内自动登录的功能.同时还介绍"如果校验失败则跳转到登录页面,在输入用户名.密码等完成登录之后又自动跳转到原页面"的功能实现 本次测试环境是SSM框架,在正式介绍本篇文章之前,建议需要熟悉以下前置知识点: Mybatis中使用mybatis-generator结合Ant脚本快速自动生成Model.Mapper等文件(PS:这是为了快速生成一些基本文件)   https://www

第五节 关于SpringMVC中Ajax的配置和应用[下午]

成熟,不是学会表达,而是学会咽下,当你一点一点学会克制住很多东西,才能驾驭好人生. 还有一周,祥云19就算结算了,一个半月的相处希望,胖先生算一个合格的老师 小白,小蔡,2婷婷,小猴,小恒,小崔,小龙,小姜,小翔 --胖先生  83604162 AJAX即"Asynchronous,Javascript+XML"(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.AJAX=异步JavaScript和XML(标准通用标记语言的子集).AJAX是一种用于创建快速