文件上传下载功能

package com.bjsasc.betech.web.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 该方法用于处理文件上传及下载的相关操作
 * 主要方法来源于网站:<a href="http://blog.csdn.net/geloin/article/details/7537425/">上传及下载 </a></br>
 * 参考 <a href="http://blog.csdn.net/u012604367/article/details/50516726">demo</a></br>
 * 参考<a href="http://www.cnblogs.com/oygg/p/5845204.html">FormData相关说明</a>
 *
 */
public class FileOperateUtil {
	//声明相关的变量
	public static final String REALNAME = "realName";
	public static final String STORENAME = "storeName";
	public static final String UPLOADDIR = "uploadDir/";
	private static Logger logger = (Logger) LoggerFactory.getLogger(FileOperateUtil.class);

	/**
	 * 功能描述:用于传输的文件名称转成系统存储的名称
	 * @version 1.0.0
	 */
	public static String rename(String name) {

		Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); // 生成唯一的编码
		Long random = (long) (Math.random() * now);//生成一个随机数
		String fileName = now + "" + random;
		if (name.indexOf(".") != -1) {
			fileName += name.substring(name.lastIndexOf("."));
		}
		logger.info("传入的文件名称为:"+name);
		logger.info("传出的文件名称为:"+fileName);
		return fileName;
	}

	/**
	 * 功能描述:对文件进行压缩后生成的名
	 * @version 1.0.0
	 */
	public static String zipName(String name) {
		String prefix = "";
		if (name.indexOf(".") != -1) {
			prefix = name.substring(0, name.lastIndexOf("."));
		} else {
			prefix = name;
		}
		return prefix + ".zip";
	}

	/**
	 * 功能描述:通过一般的方式进行文件上传,可以同时上传多个文件
	 * @param 
	 * @return List<Map<String,String>> 返回多个文件的原始文件名以及后续文件名构成的list集合
	 */
	public static List<Map<String, String>> upload(HttpServletRequest request) throws Exception {
		// 构建返回的列表
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
		MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
		// 获取文件的映射,可以同时上传多个文件
		Map<String, MultipartFile> fileMap = mRequest.getFileMap();
		// 获取文件的上传路径,默认情况下存在项目的文件中
		String uploadDir = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.UPLOADDIR;
		// 获取文件,如果不存在的话就创建一个
		File file = new File(uploadDir);
		if (!file.exists()) {
			file.mkdir();
		}
		Iterator<Entry<String, MultipartFile>> ite = fileMap.entrySet().iterator();
		while (ite.hasNext()) {
			Map<String, String> map = new HashMap<String, String>();
			// 获取本次的map值
			Entry<String, MultipartFile> entry = ite.next();
			// 获取对应的文件
			MultipartFile mFile = entry.getValue();
			// 获取文件的初始名称
			String fileName = mFile.getOriginalFilename();

			// 生成文件的存储名称
			String storeName = rename(fileName);
			File newfile = new File(uploadDir + storeName);
			BufferedOutputStream outputstream = new BufferedOutputStream(new FileOutputStream(newfile));
			FileCopyUtils.copy(mFile.getInputStream(), outputstream);
			// 将文件的信息放入到Map中去
			map.put(FileOperateUtil.STORENAME, storeName);
			map.put(FileOperateUtil.REALNAME, fileName);
			result.add(map);
		}
		return result;
	}
	/**
	 * 
	 * 功能描述:通过SpringMVC的MultipartFile上传文件,可以用于ajax局部上传
	 * @param 
	 * @return Map<String,String> 返回原始的文件名以及存储在系统中的文件名构成的MAP
	 */
	public static Map<String, String> upload(HttpServletRequest request, MultipartFile files) throws Exception {
		// 构建返回的列表
		Map<String, String> result = new HashMap<String,String>();
		// 获取文件的上传路径,默认情况下存在项目的文件中
		String uploadDir = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.UPLOADDIR;
		// 获取文件,如果不存在的话就创建一个
		File file = new File(uploadDir);
		if (!file.exists()) {
			file.mkdir();
		}
		//获取上传文件的名称
		String fileName = files.getOriginalFilename();
		// 生成文件的存储名称
		String storeName = FileOperateUtil.rename(fileName);
		//构建新的文件
		File newfile = new File(uploadDir + storeName);
		BufferedOutputStream outputstream;
		try {
			outputstream = new BufferedOutputStream(new FileOutputStream(newfile));
			try {
				FileCopyUtils.copy(files.getInputStream(), outputstream);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		result.put(FileOperateUtil.REALNAME, fileName);
		result.put(FileOperateUtil.STORENAME, storeName);
		return result;
	}

	/**
	 * 功能描述:用于进行文件的下载
	 * @param  storeName 存储名称  
	 * @return void
	 */
	public static void download(HttpServletRequest request, HttpServletResponse response, String storeName,
			String realName) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null; // 输入流
		BufferedOutputStream bos = null; // 输出流

		String ctxPath = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.UPLOADDIR;
		String downLoadPath = ctxPath + storeName;// 获取文件的下载路径

		long fileLength = new File(downLoadPath).length();// 获取文件的大小

		response.setContentType("application/octet-stream");
		response.setHeader("Content-disposition",
				"attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));

		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		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);
		}
		bis.close();
		bos.close();
	}
	/**
	 * 功能描述:根据路径删除文件
	 * @param 
	 * @return boolean
	 */
	public static boolean deleteFileByPath(String path){
		boolean flag=false;
		File file=new File(path);
		if(!file.exists()){
			return flag;
		}else{
			if(file.isFile()){
				file.delete();
				flag=true;
			}
		}
		return flag;
	}
	public static boolean deleteFileByName(HttpServletRequest request,String storename){
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.UPLOADDIR;
		String deletePath = ctxPath + storename;// 获取文件的下载路径
		return deleteFileByPath(deletePath);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值