java上传文件到项目

package util.tool;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
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.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import util.config.Caller;

public class FileUtil {
	
	public final static ServletContext sc = ContextLoader.getCurrentWebApplicationContext().getServletContext();

	public final static String PRE_PATH = sc.getRealPath("");

	public final static String UTIL_PATH = "/document/util/";
	
	
	public static List<Map<String,String>> saveFile(HttpServletRequest req,String thisPath) throws Exception{
		List<MultipartFile> fList = upload(req);
		List list = new ArrayList();
		if (fList.size() == 0)
			return list;
		for (MultipartFile file : fList) {
			// 取得当前上传文件的文件名称
			String myFileName = file.getOriginalFilename();
			String name = file.getName();

			// 重命名上传后的文件名
			String fileName = UUID.randomUUID().toString();

			fileName += myFileName.substring(myFileName.indexOf("."));

			// 定义上传路径
			if (thisPath == null)
				thisPath = UTIL_PATH;
			String path = PRE_PATH + thisPath + fileName;
			String relativePath = thisPath + fileName;
			File localFile = new File(path);
			file.transferTo(localFile);
			// 保存附件信息
			Map map = new HashMap();
			map.put("relativePath", relativePath);
			map.put("fileName", myFileName);
			map.put("filePath", path);
			map.put("name", name);
			list.add(map);

		}

		return list;
	}

	// 文件上传,传入request请求对象,返回组装成的文件的集合
	private static List<MultipartFile> upload(HttpServletRequest req)
			throws Exception {
		List<MultipartFile> list = new ArrayList<MultipartFile>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				sc);

		// 判断 req 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(req)) {
			// 转换成多部分req
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) req;
			// 取得req中的所有文件名

			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null && (file.getOriginalFilename().trim() != "")) {
					list.add(file);
				}

			}

		}
		return list;
	}

	public static int saveFile(HttpServletRequest req, String thisPath,
			Caller caller) throws Exception {

		List<MultipartFile> fList = upload(req);

		int count = 0;

		if (fList.size() == 0)
			return 0;
		for (MultipartFile file : fList) {
			// 取得当前上传文件的文件名称
			String myFileName = file.getOriginalFilename();
			String delTypeFlieName = myFileName.substring(0,
					myFileName.indexOf("."));
			String name = file.getName();

			// 重命名上传后的文件名
			String fileName = UUID.randomUUID().toString();

			fileName += myFileName.substring(myFileName.indexOf("."));

			// 定义上传路径
			if (thisPath == null)
				thisPath = UTIL_PATH;
			String path = PRE_PATH + thisPath + fileName;
			String relativePath = thisPath + fileName;
			File localFile = new File(path);
			file.transferTo(localFile);
			// 保存附件信息
			Map map = new HashMap();
			map.put("relativePath", relativePath);
			map.put("fileName", delTypeFlieName);
			map.put("filePath", path);
			map.put("name", name);
			caller.call(map);
			count++;

		}

		return count;
	}

	public static ResponseEntity<byte[]> download(String path, String fileName)
			throws Exception {
		String[] ps = path.split("/");
		File file = new File(path);
		if (file != null) {
			HttpHeaders headers = new HttpHeaders();
			// String fileName = p;
			fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");// 为了解决中文名称乱码问题
			headers.setContentDispositionFormData("attachment", fileName);
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			return new ResponseEntity<byte[]>(
					FileUtils.readFileToByteArray(file), headers,
					HttpStatus.OK);
		}

		return null;
	}

	/**
	 * 导入功能
	 * 
	 * @param request
	 *            ,回调函数
	 * @author zhengcj
	 * @return boolean
	 * @throws Exception
	 */
	public static List<List<String>> fileImport(HttpServletRequest req)
			throws Exception {
		List<List<String>> columns = new ArrayList<List<String>>();
		List<MultipartFile> files = upload(req);
		// 先判断是否存在文件
		if (files.size() == 0)
			return null;
		for (MultipartFile file : files) {
			InputStream is = file.getInputStream();

			POIFSFileSystem fs = new POIFSFileSystem(is);
			HSSFWorkbook wb = new HSSFWorkbook(fs);
			HSSFSheet sheet = wb.getSheetAt(0);
			HSSFRow row = sheet.getRow(0);

			// 得到总行数
			int rowNum = sheet.getLastRowNum();最后一行行标,比行数小1
			int colNum = row.getPhysicalNumberOfCells();//是获取不为空的列个数。
			
			// 正文内容应该从第二行开始,第一行为表头的标题
			for (int i = 0; i <= rowNum; i++) {
				row = sheet.getRow(i);
				List<String> column = new ArrayList<String>();
				String[] col = new String[colNum];
				for (int j = 0; j < colNum; j++) {
					String d = getCellFormatValue(row.getCell(j)).trim();
					column.add(d);

				}
				columns.add(column);
			}
		}
		return columns;
	}

	public static String getCellFormatValue(HSSFCell cell) {
		String cellvalue = "";
		if (cell != null) {
			// 判断当前Cell的Type
			switch (cell.getCellType()) {
			// 如果当前Cell的Type为NUMERIC
			case HSSFCell.CELL_TYPE_NUMERIC:
			case HSSFCell.CELL_TYPE_FORMULA: {
				// 判断当前的cell是否为Date
				if (HSSFDateUtil.isCellDateFormatted(cell)) {
					// 如果是Date类型则,转化为Data格式

					// 方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00
					// cellvalue = cell.getDateCellValue().toLocaleString();

					// 方法2:这样子的data格式是不带带时分秒的:2011-10-12
					Date date = cell.getDateCellValue();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					cellvalue = sdf.format(date);

				}
				// 如果是纯数字
				else {
					// 取得当前Cell的数值
					DecimalFormat df = new DecimalFormat("#.######");  
              	  
                	String whatYourWant = df.format(cell.getNumericCellValue());  
                    cellvalue = String.valueOf(whatYourWant);
				}
				break;
			}
			// 如果当前Cell的Type为STRIN
			case HSSFCell.CELL_TYPE_STRING:
				// 取得当前的Cell字符串
				cellvalue = cell.getRichStringCellValue().getString();
				break;
			// 默认的Cell值
			default:
				cellvalue = " ";
			}
		} else {
			cellvalue = "";
		}
		return cellvalue;
	}

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值