文件下载-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成功");
	}
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。