文件下载-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) {
		} 
	}

	//传送文件流到client
	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成功"); } }



posted @ 2016-01-07 19:02  phlsheji  阅读(249)  评论(0编辑  收藏  举报