文件上传下载预览
package com.xxxx.mdata.utils;
import cn.ewsd.common.utils.BaseUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class FileUploadUtils {
public static Map<String, Object> upload(HttpServletRequest request) throws Exception {
request.setCharacterEncoding("UTF-8");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,zip,rar,gz,bz2,pdf");
Map<String, Object> returnMap = new HashMap<String, Object>();
String fileName;
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 上传文件
MultipartFile mf = entity.getValue();
long fileSize = mf.getSize();
fileName = mf.getOriginalFilename();
//fileName = URLDecoder.decode(fileName, "UTF-8");
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 获得文件类型,放入相应的文件夹
String fileType = "";
Boolean allowUpload = false;
for (Map.Entry<String, String> vo : extMap.entrySet()) {
if (vo.getValue().indexOf(fileExt) > -1) {
fileType = vo.getKey();
allowUpload = true;
break;
}
}
if (!allowUpload) {
returnMap.put("statusCode", "300");
returnMap.put("title", "操作提示");
returnMap.put("message", "不允许上传该类文件!");
return returnMap;
}
fileType = "".equals(fileType) ? "file" : fileType;
String uploadDir = getUploadDir(fileType);
// 创建文件夹
File file = new File(uploadDir);
if (!file.exists()) {
file.mkdirs();
}
// 生成保存到服务器的文件名
String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date()) + "_" + BaseUtils.getFixLengthNum(10000, 99999) + "." + fileExt;
File uploadFile = new File(uploadDir + "/" + newFileName);
uploadDir = uploadDir.replace("\\", "/");
try {
FileCopyUtils.copy(mf.getBytes(), uploadFile);
// save("uplodify", request.getParameter("module"), request.getParameter("category"), request.getParameter("puuid"), fileExt, fileSize, fileName, newFileName, uploadDir.substring(uploadDir.indexOf("uploads") - 1) + newFileName);
String filepath = "/" + uploadDir.substring(uploadDir.indexOf("uploads")) + newFileName;
returnMap.put("statusCode", "200");
returnMap.put("title", "操作提示");
returnMap.put("message", "上传成功");
returnMap.put("imgs",filepath);
returnMap.put("name",fileName);
} catch (IOException e) {
e.printStackTrace();
returnMap.put("statusCode", "300");
returnMap.put("title", "操作提示");
returnMap.put("message", "上传失败");
}
}
return returnMap;
}
public static String getUploadDir(String filtType) {
//String ctxPath = request.getSession().getServletContext().getRealPath("/") + "uploads";
String uploadDir = System.getProperty("user.dir") + "/uploads/" + filtType;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy" + File.separator + "MM" + File.separator + "dd");
Date date = new Date();
String ymd = sdf.format(date);
uploadDir += File.separator + ymd + File.separator;
return uploadDir;
}
/**
* [getFileType 下载文档对应的类型]
*/
public static String getFileType(String key) {
Map<String, FileType> fileTypeMap = new HashMap<>();
fileTypeMap.put("doc", new FileType("doc", "application/msword"));
fileTypeMap.put("docx", new FileType("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
fileTypeMap.put("dot", new FileType("dot", "application/msword"));
fileTypeMap.put("dotx", new FileType("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"));
fileTypeMap.put("xls", new FileType("xls", "application/vnd.ms-excel"));
fileTypeMap.put("xlsx", new FileType("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
fileTypeMap.put("ppt", new FileType("ppt", "application/vnd.ms-powerpoint"));
fileTypeMap.put("pptx", new FileType("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"));
fileTypeMap.put("pdf", new FileType("pdf", "application/pdf"));
fileTypeMap.put("txt", new FileType("txt", "text/plain"));
fileTypeMap.put("gif", new FileType("gif", "image/gif"));
fileTypeMap.put("jpeg", new FileType("jpeg", "image/jpeg"));
fileTypeMap.put("jpg", new FileType("jpg", "image/jpeg"));
fileTypeMap.put("png", new FileType("png", "image/png"));
fileTypeMap.put("css", new FileType("css", "text/css"));
fileTypeMap.put("html", new FileType("html", "text/html"));
fileTypeMap.put("htm", new FileType("htm", "text/html"));
fileTypeMap.put("xsl", new FileType("xsl", "text/xml"));
fileTypeMap.put("xml", new FileType("xml", "text/xml"));
fileTypeMap.put("mpeg", new FileType("mpeg", "video/mpeg"));
fileTypeMap.put("mpg", new FileType("mpg", "video/mpeg"));
fileTypeMap.put("avi", new FileType("avi", "video/x-msvideo"));
fileTypeMap.put("movie", new FileType("movie", "video/x-sgi-movie"));
fileTypeMap.put("bin", new FileType("bin", "application/octet-stream"));
fileTypeMap.put("exe", new FileType("exe", "application/octet-stream"));
fileTypeMap.put("so", new FileType("so", "application/octet-stream"));
fileTypeMap.put("dll", new FileType("dll", "application/octet-stream"));
fileTypeMap.put("ai", new FileType("ai", "application/postscript"));
fileTypeMap.put("dir", new FileType("dir", "application/x-director"));
fileTypeMap.put("js", new FileType("js", "application/x-javascript"));
fileTypeMap.put("swf", new FileType("swf", "application/x-shockwave-flash"));
fileTypeMap.put("xhtml", new FileType("xhtml", "application/xhtml+xml"));
fileTypeMap.put("xht", new FileType("xht", "application/xhtml+xml"));
fileTypeMap.put("zip", new FileType("zip", "application/zip"));
fileTypeMap.put("mid", new FileType("mid", "audio/midi"));
fileTypeMap.put("midi", new FileType("midi", "audio/midi"));
fileTypeMap.put("mp3", new FileType("mp3", "audio/mpeg"));
fileTypeMap.put("rm", new FileType("rm", "audio/x-pn-realaudio"));
fileTypeMap.put("rpm", new FileType("rpm", "audio/x-pn-realaudio-plugin"));
fileTypeMap.put("wav", new FileType("wav", "audio/x-wav"));
fileTypeMap.put("bmp", new FileType("bmp", "image/bmp"));
FileType fileType = fileTypeMap.get(key);
if (fileType != null) {
return fileType.getApplication();
}else {
return "application/octet-stream";
}
}
}
class FileType {
private String type;
private String application;
public FileType(String type, String application) {
this.type = type;
this.application = application;
}
public String getType() {
return type;
}
public String getApplication() {
return application;
}
}
@RequestMapping(value = "/download.api",method = RequestMethod.GET)
public void download(HttpServletRequest req, HttpServletResponse response) throws IOException {
String uuid = req.getParameter("uuid");
ZcglDetailImgs zcglDetailImgs = zcglDetailImgsMapper.selectByPrimaryKey(uuid);
String filePath = zcglDetailImgs.getImgs();
String path = System.getProperty("user.dir") + filePath;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
String fileName = zcglDetailImgs.getName();
inputStream = new FileInputStream(path);
outputStream = response.getOutputStream();
//文件后缀
String fileType = filePath.substring(filePath.lastIndexOf(".") + 1).toLowerCase();
//获取对应的响应类型
String resFileType = FileUploadUtils.getFileType(fileType);
response.setContentType(resFileType);
response.setHeader("Content-Length", String.valueOf(inputStream.available()));
//Content-Disposition值为inline时,浏览器预览
//Content-Disposition值为attachment时,下载
response.addHeader("Content-Disposition", "inline;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); //解决乱码
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.close();
inputStream.close();
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
}