上传组件 (自定义异常展示信息) UploadFileService
注意自定义异常的使用及方法的抽取。
try {
} catch (Exception e) {
e.printStackTrace();
logger.error("generate error : " + e.getMessage());
throw new ConvertsServiceException(e.getMessage());
}
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service("iUploadFileService")
public class UploadFileService implements IUploadFileService {
private static final Logger logger = LoggerFactory.getLogger(UploadFileService.class);
@Autowired
private IEsbFileDao esbFileDao;
@Autowired
private ISysFileDao sysFileDao;
@Override
public EsbFile saveFile(MultipartFile file, String[] allowExtName,
long maxLength, String module) throws UploadFileException {
logger.debug("saveFile begin...");
// 校验文件
validateFile(file, allowExtName, maxLength);
logger.debug("validateFile pass...");
// 获取时间戳
String time = System.currentTimeMillis() + "";
// 拼装服务端文件存储路径
String ext = FilenameUtils.getExtension(file.getOriginalFilename());
ext = "".equals(ext) ? "" : ("." + ext);
String path = new StringBuilder(
SystemConfiguration.getConfigByName(Constants.SYSTEM_FILE_PATH))
.append(File.separator).append(time).append(File.separator)
.append(time).append(ext).toString();
logger.debug("savedFilePath : " + path);
// 保存文件
File savedFile = new File(path);
try {
FileUtils.writeByteArrayToFile(savedFile, file.getBytes());
} catch (IOException e) {
// 保存文件出错
throw new UploadFileException(
"\u4fdd\u5b58\u6587\u4ef6\u51fa\u9519");
}
logger.debug("writeByteArrayToFile pass...");
// 将文件信息存储到数据中
// sysfile
SysFile sf = new SysFile();
sf.setOriFileName(file.getOriginalFilename());
sf.setServerAbsPath(path);
sf.setFileSize(file.getSize());
try {
sf.setMd5CheckSum(MD5Util.getMD5(savedFile));
} catch (Exception e) {
logger.error("MD5_CHECK_SUM error...");
e.printStackTrace();
}
ObjectUtil.setCreatedBy(sf);
sf = sysFileDao.save(sf);
// esbfile
EsbFile ef = new EsbFile();
ef.setModuleCode(module);
ef.setFileId(sf.getId());
ef.setSysFile(sf);
ObjectUtil.setCreatedBy(ef);
esbFileDao.save(ef);
logger.debug("saveFile end...");
return ef;
}
/**
* 验证上传文件是否合法,否则抛出异常
*
* @param file
* @param allowExtName null或空数组则允许所有文件
* @param maxLength 为负数则允许上传任意大小文件
* @throws UploadFileException
*/
private void validateFile(MultipartFile file, String[] allowExtName,
long maxLength) throws UploadFileException {
String fileName = "";
long fileSize = 0L;
// 验证文件为空
if (file == null || (fileName = file.getOriginalFilename()).equals("")
|| (fileSize = file.getSize()) <= 0) {
// 上传文件为空
throw new UploadFileException(
"\u4e0a\u4f20\u6587\u4ef6\u4e3a\u7a7a");
}
// 验证文件大小
if (maxLength > 0 && fileSize > maxLength) {
// 上传文件大小超出上限
throw new UploadFileException(
"\u4e0a\u4f20\u6587\u4ef6\u5927\u5c0f\u8d85\u51fa\u4e0a\u9650 ["
+ maxLength + "byte]");
}
if (allowExtName != null && allowExtName.length > 0) {
if (Arrays.binarySearch(allowExtName, FilenameUtils.getExtension(fileName).toLowerCase()) < 0) {
// 上传文件格式不符合要求
throw new UploadFileException(
"\u4e0a\u4f20\u6587\u4ef6\u683c\u5f0f\u4e0d\u7b26\u5408\u8981\u6c42 "
+ Arrays.toString(allowExtName));
}
}
}
}
public class UploadFileException extends Exception {
private static final long serialVersionUID = -7352737478882318028L;
public UploadFileException() {
super();
}
public UploadFileException(String message, Throwable cause) {
super(message, cause);
}
public UploadFileException(String message) {
super(message);
}
public UploadFileException(Throwable cause) {
super(cause);
}
}
调用:
@RequestMapping(value="/esbService/uploadTemplet.do", method = RequestMethod.POST)
@ResponseBody
public void uploadTemplet(@RequestParam MultipartFile file, HttpSession session, HttpServletResponse response){
// 返回值
Map<String, Object> result = new HashMap<String, Object>(2);
EsbFile esbfile = null;
// 上传文件保存
try {
esbfile = upFileDS.saveFile(file, new String[]{"doc", "docx", "zip"}, -1, "SRV_DEFINE.IMPORT_DOC");
} catch (UploadFileException e) {
result.put("code", 1);
result.put("msg", e.getMessage());
writeResponse(response,result);
return;
}
// 导入规范
try {
convertsSrvDS.importWord(esbfile);
} catch (Exception e) {
result.put("code", 1);
result.put("msg", e.getMessage());
writeResponse(response,result);
return;
}
result.put("code", 0);
writeResponse(response,result);
}
private void writeResponse(HttpServletResponse response, Map<String, Object> result) {
try {
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(JSON.toJson(result));
response.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
以前代码:
public class TempletUploadUtil {
private static final Logger logger = LoggerFactory.getLogger(TempletUploadUtil.class);
public static Map<String, Object> uploadTemplet(@RequestParam MultipartFile file, HttpSession session,
HttpServletResponse response,SysConfig env) {
Map<String, Object> result = new HashMap<String, Object>(2);
String newName = null;
try {
if (!file.isEmpty()) {
if (env == null || "".equals(env)) {
result.put("code", 1);
result.put("msg", "获取上传路径配置失败");
writeResponse(response, result);
return null;
}
// 时间戳为文件名保存文件
int index = file.getOriginalFilename().lastIndexOf(".");
if(index>-1){
newName = env.getConfigValue().trim() + File.separator + System.currentTimeMillis()+ File.separator + file.getOriginalFilename();
}else{
newName = env.getConfigValue().trim() + File.separator + String.valueOf(System.currentTimeMillis());
}
if(!isAllowedFileType(newName)){
result.put("code", 3);
result.put("msg", "文件类型不允许!");
writeResponse(response,result);
return null;
}
// newName = file.getName()+"_"+newName;
// 写文件
FileUtils.writeByteArrayToFile(new File(newName), file.getBytes());
String loc = new File(newName).getAbsolutePath();
result.put("code", 0);
result.put("msg", loc);
}
} catch (IOException e) {
logger.error("文件上传失败:", e);
result.put("code", 2);
result.put("msg", "文件上传失败!");
writeResponse(response, result);
return null;
}
return result;
}
private static void writeResponse(HttpServletResponse response, Map<String, Object> result) {
try {
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(JSON.toJson(result));
response.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private static Boolean isAllowedFileType(String newName){
String ext = newName.substring(newName.lastIndexOf(".")+1);
String allowType = "wsdl,zip,rar";
return allowType.indexOf(ext.toLowerCase()) >= 0;
}
}