FileUploadController.java
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* Created by yz.shi on 2018/3/15.
*/
@Controller
public class FileUploadController {
private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
@Value("${shop.back.uploadUrl}")
private String uploadUrl;
@Value("${shop.back.uploadDir}")
private String uploadDir;
/**
* 上次文件(先到临时目录)
*
* @param uploadFile
* @param request
* @param response
* @return
*/
@RequestMapping("/uploadTempImport_backuser")
public ModelAndView uploadTempImport(MultipartFile uploadFile, HttpServletRequest request,
HttpServletResponse response) {
JSONObject json = new JSONObject();
try {
json.put("result", false);
String originalFilename = uploadFile.getOriginalFilename();
String newFileName = FileUtil.getRandomFileName(originalFilename);
String tempPath = uploadDir + "//temp//";
FileUtil.mkdirs(tempPath);
File newFile = new File(tempPath, newFileName);
uploadFile.transferTo(newFile);
String streamPath = uploadUrl + "temp/" + newFileName;
json.put("fileName", newFileName);
json.put("result", true);
json.put("fileUrl", streamPath);
} catch (Exception e) {
logger.error("文件上传失败:", e);
}
return new ModelAndView("/result.jsp").addObject("json", json.toString());
}
/**
* 下载文件
*
* @param modelName
* @param fileName
* @param response
* @return
* @throws IOException
*/
@RequestMapping("/downByPath_backuser")
public String downByPath(String modelName, String fileName, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
try {
InputStream inputStream = new FileInputStream(
new File(uploadDir + File.separator + modelName + File.separator + fileName));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
inputStream.close();
} catch (Exception e) {
logger.error("文件上传失败:", e);
}
return null;
}
}
shop.back.uploadDir = E:\\workspace\\shop-static\\src\\main\\webapp\\upmall\\ shop.back.uploadUrl= http://static.com/upmall/
FileUtil.java
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by yz.shi on 2018/3/15.
*/
public class FileUtil {
public static String PATH_SEPARATE = "/";
/**
* 创建目录
*
* @param dirPath
*/
public static void mkdirs(String dirPath) {
File dirFile = new File(dirPath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
}
/**
* 删除文件
*
* @param filePath
*/
public static boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return true;
}
return file.delete();
}
public static boolean deleteDirectory(String dirPath) {
return deleteDirectory(new File(dirPath));
}
/**
* 删除文件和目录
*
* @param file
* @return
*/
public static boolean deleteDirectory(File file) {
if (!file.exists()) {
return true;
}
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
for (File childrenFile : listFiles) {
FileUtil.deleteDirectory(childrenFile);
}
}
return file.delete();
}
/**
* 获取一个随机的文件名
*
* @param realFilename
* @return
*/
public static String getRandomFileName(String realFilename) {
String newFileName = Calendar.getInstance().getTimeInMillis() + RandomUtil.getNumberCode(4);
int index = realFilename.lastIndexOf(".");
if (index >= 0) {
newFileName += realFilename.substring(index);
}
return newFileName;
}
/**
* 获取一个新文件对象,存在先删除
*
* @param filePath
* @return
*/
public static File getNewFile(String filePath) {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
return file;
}
/**
* 创建一个文件,如果文件存在就先删除再创建一个新的
*
* @param filePath 文件完整路径
* @return 返回新创建的文件
*/
public static File createNewFile(String filePath) {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
return file;
}
/**
* 生成带版本号的文件名
*
* @param fileName
* @param
* @return
*/
public static String getFileVersionName(String fileName, int version) {
int index = fileName.lastIndexOf(".");
return fileName.substring(0, index) + version + fileName.substring(index);
}
/**
* 检查文件路径是否存在
*
* @param filePath
* @return
*/
public static boolean checkFileExist(String filePath) {
File file = new File(filePath);
return file.exists();
}
/**
* 返回文件的扩展名
*
* @param fileName
* @return
*/
public static String getExtension(String fileName) {
return getExtension(fileName, "");
}
public static String getExtension(String fileName, String ext) {
if (fileName != null && fileName.length() > 0) {
int i = fileName.lastIndexOf(".");
if (i > -1 && i < (fileName.length() - 1)) {
return fileName.substring(i + 1);
}
}
return ext;
}
/**
* 根据文件读取txt内容
*
* @param pathname
* @return
*/
public static List getListByTxt(String pathname) {
List<String> list = new ArrayList<String>();
File filename = new File(pathname); // 要读取以上路径的input。txt文件
InputStreamReader reader = null; // 建立一个输入流对象reader
try {
reader = new InputStreamReader(
new FileInputStream(filename));
BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言
String line = "";
line = br.readLine();
if (StringUtil.isNotNullStr(line)) {
list.add(line);
}
while (line != null) {
line = br.readLine(); // 一次读入一行数据
if (StringUtil.isNotNullStr(line)) {
list.add(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* getResponseEntity
*
* @param fileName
* @param fileBytes
* @return
* @throws UnsupportedEncodingException
*/
public static ResponseEntity<byte[]> getResponseEntity(String fileName,
byte[] fileBytes) throws UnsupportedEncodingException {
HttpHeaders headers = new HttpHeaders();
// 设置文件名
headers.setContentDispositionFormData("attachment",
new String(fileName.getBytes("gb2312"), "iso-8859-1"));
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(fileBytes, headers, HttpStatus.OK);
}
}
导出excel:
/**
* 导出
*
* @param query
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = {"/exportPurchaseRecord"})
public
@ResponseBody
ResponseEntity<byte[]> exportPurchaseRecord(PurchaseRecordQuery query) throws UnsupportedEncodingException {
List<PurchaseRecord> list = this.bo.exportPurchaseRecord(query);//查数据库
LinkedHashMap<String, String> columnMap = new LinkedHashMap<String, String>();
columnMap.put("订单号", "purchaseNo");
columnMap.put("支付号", "orderNo");
columnMap.put("会员账号", "name");
columnMap.put("会员手机号", "mobile");
columnMap.put("下单时间", "addTime");
columnMap.put("订单状态", "statusStr");
columnMap.put("支付金额", "totalPrice");
columnMap.put("支付时间", "payTime");
columnMap.put("订单商品描述", "productName");
byte[] exportData = ExportUtil.exportStr(columnMap, list);
return FileUtil.getResponseEntity("gamelife-mall-order.csv", exportData == null ? new byte[0] : exportData);
}
ExportUtil.java
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 导出辅助类
*/
public class ExportUtil {
private static Logger log = Logger.getLogger(ExportUtil.class);
/**
* 导出方法入口,把结果集处理成byte[]数据,传入参数labelValueMap,放入[表头:pojo对应字段]
*
* @param labelValueMap
* @param dataList
* @return
*/
public static byte[] exportStr(LinkedHashMap<String, String> labelValueMap, List<?> dataList) {
if (CollectionUtil.isEmpty(dataList) || labelValueMap == null || labelValueMap.size() == 0) {
return null;
}
LinkedHashMap<String, Method> methodMap = new LinkedHashMap<String, Method>();
Class<?> clazz = dataList.get(0).getClass();
for (Map.Entry<String, String> entry : labelValueMap.entrySet()) {
String methodName = entry.getValue();
if (StringUtils.isBlank(methodName)) {
continue;
} else if (!methodName.startsWith("get")) {
methodName = "get" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
}
try {
Method m = clazz.getMethod(methodName);
methodMap.put(entry.getKey(), m);
} catch (Exception e) {
continue;
}
}
return exportMethod(methodMap, dataList);
}
/**
* 导入方法入口,一般用隔壁那个exportDataStr更为简便
*
* @param map
* @param dataList
* @return
*/
public static byte[] exportMethod(LinkedHashMap<String, Method> map, List<?> dataList) {
if (CollectionUtil.isEmpty(dataList) || map == null || map.size() == 0) {
return null;
}
ByteArrayOutputStream outputStream = null;
DataOutputStream dataOutputStream = null;
try {
Set<String> keySet = map.keySet();
outputStream = new ByteArrayOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
String columnJoin = StringUtils.join(keySet.iterator(), ",") + "\n";
dataOutputStream.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
dataOutputStream.write(columnJoin.getBytes("utf-8"));
for (Object obj : dataList) {
if (obj == null) {
continue;
}
Stack<String> stack = new Stack<String>();
for (Method m : map.values()) {
Object value = m.invoke(obj);
if (value == null) {
stack.push("");
} else {
stack.push(csvHandlerStr(value.toString()));
}
}
String valueJoin = StringUtils.join(stack.iterator(), ",") + "\n";
dataOutputStream.write(valueJoin.getBytes("utf-8"));
}
return outputStream.toByteArray();
} catch (Exception e) {
log.error("文件导出异常", e);
return null;
} finally {
if (null != dataOutputStream) {
try {
dataOutputStream.close();
} catch (IOException e) {
log.error("close outputStreamWriter error.", e);
}
}
if (null != outputStream) {
try {
outputStream.close();
} catch (IOException e) {
log.error("outputStream close error.", e);
}
}
}
}
/**
* csv特殊字符转译
*
* @param htmlStr
* @return
*/
public static String csvHandlerStr(String htmlStr) {
String str = getTextFromHtml(htmlStr);
// csv格式如果有逗号,整体用双引号括起来;如果里面还有双引号就替换成两个双引号,这样导出来的格式就不会有问题了
String tempDescription = str;
// 如果有逗号
if (str.contains(",")) {
// 如果还有双引号,先将双引号转义,避免两边加了双引号后转义错误
if (str.contains("\"")) {
tempDescription = str.replace("\"", "\"\"");
}
// 在将逗号转义
tempDescription = "\"" + tempDescription + "\"";
}
return tempDescription;
}
/**
* TextFromHtml
*
* @param htmlStr
* @return
*/
public static String getTextFromHtml(String htmlStr) {
return delHTMLTag(htmlStr).replaceAll(" ", " ").replaceAll("\n", " ").replaceAll("\r", " ")
.replaceAll("\t", " ");
}
/**
* delHTMLTag
*
* @param htmlStr
* @return
*/
public static String delHTMLTag(String htmlStr) {
// 定义HTML标签的正则表达式
Pattern p_html = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
return htmlStr.trim(); // 返回文本字符串
}
}