`
uule
  • 浏览: 6342081 次
  • 性别: Icon_minigender_1
  • 来自: 一片神奇的土地
社区版块
存档分类
最新评论

上传组件 (自定义异常展示信息) 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;  
	}

}

 

 

 

 

 

分享到:
评论

相关推荐

    自定义异常

    如果这个组件支持异常处理,那么开发者可能会在自定义异常上下文中使用它,例如,当用户在界面上输入无效数据时抛出自定义异常。 总结来说,自定义异常是软件开发中的重要实践,它允许我们定制错误处理策略,使代码...

    基于layui自定义表单组件

    在C#开发中,layui自定义表单组件通常用于构建前端展示层,与后端数据进行交互。这涉及到以下几个知识点: 1. **前后端分离**:C#作为后端语言处理业务逻辑和数据操作,通过RESTful API向layui前端发送数据。前端则...

    uni-app 自定义组件展示html富文本内容,可实现富文本html内容中 图片展示、视频播放、音频播放。

    1. 图片展示:自定义组件可以通过接收JSON中的图片信息,使用uni-app的组件来显示图片,同时处理图片的点击事件、懒加载等功能。 2. 视频播放:对于视频,可以使用uni-app的组件来播放。自定义组件需要解析JSON中的...

    Office2016组件自定义安装程序.7z

    Office2016组件自定义安装程序.7z

    Qt美化界面、美化组件、自定义组件源码

    "Qt美化界面、美化组件、自定义组件源码"这个主题涵盖了提升Qt应用视觉效果和功能定制的核心知识点。Qt库提供了丰富的功能,允许开发者创建出优雅且高效的应用程序,而不仅仅是基本的用户界面。 首先,Qt美化界面...

    vue iView 上传组件之手动上传功能

    iView的上传组件 `&lt;Upload&gt;` 提供了多种配置项,如`multiple`、`before-upload`、`show-upload-list`、`on-success` 和 `action`等,这些参数和方法有助于实现各种自定义功能。 1. **multiple**:这个属性用于设置...

    使用微搭自定义组件实现搜索组件 .docx

    使用微搭自定义组件实现搜索组件 微搭作为一款低代码开发平台,可以快速完成页面的搭建,但官方提供的组件可能和业务还有一定的距离。为了满足开发者的需求,微搭提供了自定义组件的能力,支持低码组件和源码组件。...

    ActionScript的自定义组件及自定义事件例子

    在本实例中,我们将深入探讨如何在ActionScript中实现自定义组件和自定义事件,这对于创建复杂的Flash应用程序至关重要。 首先,让我们了解自定义组件。在ActionScript中,自定义组件是通过继承已有的UIComponent...

    Winform自定义组件库

    资源为Winform用户自定义组件库,是自己平时做项目用到的组件以及参考晚上那些有特效组件封装的组件库,中间付出了很多努力,攻克了很多难点,大家喜欢的话,请大家多多给予鼓励,目前是V1.0版本,后期不断更新。...

    业务异常提示处理 springboot+Assert(自定义断言)

    6. **公共异常类**:为了规范化异常信息,通常会定义一个或多个公共异常类,比如`BusinessException`,它包含业务错误码和错误信息,这使得在抛出和捕获异常时能提供一致的信息,提高了代码的可读性。 7. **模块化...

    office2016 组件自定义安装辅助工具

    Office 2016 Install 不仅是一款在线 Office 2016 下载安装工具,还可以用于 Office 2016 离线安装包的组件自定义安装,如果你只想安装 Word/Excel/PowerPoint 或者只想安装其中一款软件,Office 2016 Install 就是...

    Vue-Vben-Admin - 自定义上传excel文件弹框组件

    在本案例中,我们关注的是一个自定义的上传Excel文件的弹框组件。这个组件允许用户选择并上传Excel文件,以便进行数据导入或其他需要处理Excel数据的操作。 在 Vue.js 中,组件是构建应用程序的基本单元,它们可以...

    vue自定义全局组件(自定义插件)的用法

    Vue自定义全局组件(自定义插件)的用法 Vue.js 提供了一种自定义全局组件的方式,使得开发者可以根据自己的需求创建自己的插件,从而提高开发效率和体验。本文将介绍 Vue 自定义全局组件的用法,并提供一个简单的...

    QML自定义组件显示在QT Designer库面板中的方法

    qmotypes文件是用于在设计时提供类型信息的文件,它让自定义组件能够在QT Designer中被识别。通过运行qmotypes指令,可以在指定的目录生成plugins.qmltypes文件,使得自定义组件可以在QT Designer的库面板中显示。 ...

    C#自定义组件

    开发者经常需要根据项目需求创建自定义组件,以提供更个性化的界面或功能。本主题将深入探讨C#中的自定义组件,特别是关于"button"和"textlist"组件的创建和使用。 1. **自定义组件的基础** - 在C#中,自定义控件...

    flex 高级自定义组件

    Flex中的高级自定义组件开发是构建复杂用户界面的关键技术,它允许开发者超越基本组件的限制,以满足特定的业务需求和视觉设计。在创建高级组件时,了解并掌握一些核心方法的重写至关重要,这些方法涉及到组件的生命...

    Android 自定义TimePicker组件

    本文将深入解析TimePicker组件,并介绍如何进行自定义,以满足更加个性化的应用需求。 首先,我们来了解TimePicker的基本用法。在Android SDK中,TimePicker分为两种模式:数字时钟(digital)和模拟时钟(analog)...

    DELPHI中自定义组件的制作方法介绍

    ### DELPHI中自定义组件的制作方法介绍 #### 一、自定义组件的重要性与应用场景 自定义组件在DELPHI编程中扮演着至关重要的角色,它不仅能够封装复杂的功能,提升代码的可读性和可维护性,还能促进代码重用,加快...

    微信小程序自定义组件--日历组件

    微信小程序自定义组件是开发微信小程序时非常关键的一部分,它允许开发者扩展小程序的功能,提高代码复用性,提升开发效率...同时,这也展示了微信小程序强大的自定义组件能力,鼓励开发者创新并构建更复杂的业务逻辑。

    Flex4自定义组件开发.pdf

    ### Flex4自定义组件开发详解 #### 一、Flex4自定义组件概述 Flex4(也称为Spark)是Adobe Flex框架的一个重要版本,它引入了许多新的特性,包括改进的组件库、性能优化以及更好的可定制性。在Flex4中,自定义组件...

Global site tag (gtag.js) - Google Analytics