文件上传下载

2,028 阅读1分钟

SpringBoot 文件上传到本地、以文件流形式下载

package org.springblade.common.utils;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.StyleSet;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;


public class FilesUtil {
	
	private final static String OS = System.getProperty("os.name").toLowerCase();
	private static String FILE_PATH;	// 文件管理模块附件路径
	private static String COMMON_PATH;	// 通用模块附件路径
	static {	//根据当前操作系统设置路径
		if(OS.indexOf("linux")>=0) {
			FILE_PATH = "/home/fileManager/";
			COMMON_PATH = "/home/commonFiles/";
		} else if (OS.indexOf("windows")>=0) {
			FILE_PATH = "D:/files/fileManager/";
			COMMON_PATH = "D:/files/commonFiles/";
		} else {
			
		}
	}
	// 设置文件大小
	private final static Long MAX_SIZE = (long) (200 * 1024 * 1024);
	 
	// 固定文件上传(PDF文件 & WORD文件 & EXCEL文件 & JPG图片)
	public static JSONObject uploadNormal(MultipartFile file) {
		JSONObject resObj = new JSONObject();
		try {
			if (file.isEmpty()||file.getSize() == 0) {
				resObj.put("success", false);
				resObj.put("msg", "文件为空!");
				return resObj;
			}
			if (file.getSize() > MAX_SIZE) {
				resObj.put("success", false);
				resObj.put("msg", "文件大小限制200M!");
				return resObj;
			}
			// 获取文件名
			String fileName = file.getOriginalFilename();
			// 获取文件的后缀名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			if (fileName.endsWith("pdf") || fileName.endsWith("docx") || fileName.endsWith("doc") || fileName.endsWith("jpg") || fileName.endsWith("xls") || fileName.endsWith("xlsx")|| fileName.endsWith("mp4")) {
				String storeName = System.currentTimeMillis() + "";
				//根据文件后缀名获取文件的类型
				String suffName = fileName.substring(fileName.lastIndexOf(".")+1);
				// 设置文件存储路径
				String path = FILE_PATH + fileName.substring(0, fileName.lastIndexOf(".")) + "_" + storeName + suffixName;
				File dest = new File(path);
				// 检测是否存在目录
				if (!dest.getParentFile().exists()) {
					dest.getParentFile().mkdirs();	//新建文件夹
				}
				file.transferTo(dest);	//文件写入
				resObj.put("success", true);
				resObj.put("msg", path);
				resObj.put("type", suffName);
				resObj.put("fileName", fileName);
				return resObj;
			}
			resObj.put("success", false);
			resObj.put("msg", "文件类型限定WORD,EXCEL,PDF, JPG,MP4文件!");
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resObj;
	}
	

	//文件下载
	public static void download(HttpServletRequest request, HttpServletResponse response, String filePath){
        try {
        	File file = new File(filePath);
        	if(!file.exists())
        		throw new Exception("404 - File not Found!");
        	// 取得文件名。
        	String fileName = file.getName();
        	InputStream fis = null;
            fis = new FileInputStream(file);
            request.setCharacterEncoding("UTF-8");	//设置字符编码
            String agent = request.getHeader("User-Agent").toUpperCase();
            //判断发出请求的浏览器
            if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
                fileName = URLEncoder.encode(fileName, "UTF-8");
            else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
				outputStream.write(b, 0, len);
            }
			outputStream.flush();
			outputStream.close();
            fis.close();
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}