com.github.hdy.common.util.FileUtil Maven / Gradle / Ivy
package com.github.hdy.common.util;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* 文件工具类
*
* @author 贺大爷
* @date 2018/6/55
*/
public class FileUtil {
/**
* 上传文件(支持多文件)
*
* @param request
* @param absolutePath 绝对路劲
*/
public static List upload(HttpServletRequest request, String absolutePath) throws IOException {
if (!new File(absolutePath).exists()) {
new File(absolutePath).mkdirs();
}
List result = new ArrayList<>();
//将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//获取multiRequest 中所有的文件名
Iterator iter = multiRequest.getFileNames();
int i = 0;
while (iter.hasNext()) {
//一次遍历所有文件
MultipartFile file = multiRequest.getFile(iter.next().toString());
String originalFileName = file.getOriginalFilename();
String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
String newFileName = IdWorker.getIdStr();
if (file != null) {
//上传
file.transferTo(new File(absolutePath + "/" + newFileName + suffix));
}
Files files = new Files();
files.setOriginalFileName(originalFileName);
files.setFileName(newFileName);
files.setSize(file.getSize());
files.setSuffix(suffix.substring(1));
files.setIndex(i);
result.add(files);
i++;
}
return result;
}
/**
* 删除文件
*
* @param fileName
*
* @return
*/
public static void deleteFile(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
} else {
file.delete();
}
}
/**
* 导出excel
*
* @param list 数据
* @param response
* @param fileName 文件名
* @param sheetName sheet名
* @param titles 表头
* @param fields 表头对应的字段
*/
public static void export(List