• spring 17-Spring框架文件上传


    • 如果需要文件上传,需要实现MultipartFile接口
    • 该接口的子类是CommonsMultipartFile:org.springframework.web.multipart.commons.CommonsMultipartFile
    • 该接口是所有上传文件公共的定义配置
    • 主要方法如下:
      • public String getContentType():取得上传文件的MIME类型
      • public boolean isEmpty():取得上传文件的原始名称
      • public void transferTo(File dest) throws IOException,IllegalStateException:保存
      • public InputStream getInputStream() throws IOException:取得上传文件的输入流对象

    1、实现上传控制

    • 在applicationContext-mvc.xml文件里面定义有上传的配置限制
    • CommonsMultipartResolver类的父类CommonsFileUploadSupport里面有两个方法:
      • public void setMaxUploadSize(long maxUploadSize):设置最大的上传文件大小
      • public void setMaxInMemorySize(int maxInMemorySize):设置每个上传文件允许使用最大内存
    <!-- 定义文件的上传配置支持 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<!-- 设置每次上传文件的最大限制 -->
    	<property name="maxUploadSize" value="5242880"/>
    	<!-- 设置每次上传占用的内存大小 -->
    	<property name="maxInMemorySize" value="4096"/>
    </bean>
    

    2、目前上传使用的是Apache的Fileupload组件,在Maven的pom.xml添加相关依赖包

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    

    3、编写错误页面

    • 一旦上传失败后立即跳转到一个错误页面上
    /pages/errors.jsp
    <h1>upload file errors</h1>
    
    • 配置Tomcat上传文件限制,修改serve.xml文件
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" maxSwallowSize="-1"/>
    
    • 配置applicationContext-mvc.xml文件
    <!-- 配置了一个全局的异常的跳转映射,只要出现了指定的错误信息,那么就跳转到指定的页面 -->
    <bean id="exceptionMapping" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    	<property name="exceptionMappings">
    		<props>
    			<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">
    				/pages/errors.jsp
    			</prop>
    		</props>
    	</property>
    </bean>
    

    4、编写上传文件保存的工具类:UploadFileUtil.java

    • 该类专门负责文件上传的保存处理
    package cn.liang.util;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.UUID;
    public class UploadFileUtil {
    	
    	/**
    	 * 进行文件的保存操作
    	 * @param srcFile 上传的原始文件数据输入流
    	 * @param destFile 要保存的目标文件路径
    	 * @return 保存成功返回true,否则返回false
    	 */
    	public static boolean save(InputStream inputStream, File desFile){
    		boolean flag = false ;
    		OutputStream output = null ;
    		if (!desFile.getParentFile().exists()) {	// 父路径不存在
    			desFile.getParentFile().mkdirs();	// 创建父路径
    		}
    		try {
    			output = new FileOutputStream(desFile) ;
    			byte data [] = new byte [2048] ;	// 每块数据的保存大小
    			int temp = 0 ;	// 保存每次的个数
    			while ((temp = inputStream.read(data)) != -1) {
    				output.write(data, 0, temp);
    			} 
    			flag = true ;
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				output.close();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    		return flag ;
    	}
    	
    	/**
    	 * 创建要保存的文件名称
    	 * @param mime	上传的图片文件名
    	 * @return
    	 */
    	public static String createFileName(String mime) {	// 需要创建一个文件名称
    		String fileName = UUID.randomUUID() + "." + mime.split("/")[1] ;
    		return fileName ;
    	}
    }
    

    5、编写Action的公共类AbstractAction

    package cn.liang.util.action;
    import java.io.File;
    import java.text.SimpleDateFormat;
    import java.util.Locale;
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.context.MessageSource;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.InitBinder;
    import org.springframework.web.multipart.MultipartFile;
    import cn.liang.util.UploadFileUtil;
    
    public abstract class AbstractAction {
    	@Resource
    	private MessageSource msgSource ;	// 表示此对象直接引用配置好的类对象(根据类型匹配)
    	
    	/**
    	 * 根据指定的key的信息进行资源数据的读取控制
    	 * @param msgKey 表示要读取的资源文件的key的内容
    	 * @return 表示资源对应的内容
    	 */
    	public String getValue(String msgKey,Object ...args) {
    		return this.msgSource.getMessage(msgKey, args, Locale.getDefault()) ;
    	} 
    	
    	@InitBinder	
    	public void initBinder(WebDataBinder binder) {	// 方法名称自己随便写
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
    		// 本方法的处理指的是追加有一个自定义的转换编辑器,如果遇见的操作目标类型为java.util.Date类
    		// 则使用定义好的SimpleDateFormat类来进行格式化处理,并且允许此参数的内容为空
    		binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(sdf, true));
    	} 
    	
    	/**
    	 * 生成图片名称
    	 * @param photoFile	上传上来的图片文件对象
    	 * @return
    	 */
    	public String createFileName(MultipartFile photoFile){
    		if (photoFile.isEmpty()) {
    			return "nophoto.png";
    		}else {
    			return UploadFileUtil.createFileName(photoFile.getContentType());
    		}
    	}
    	
    	/**
    	 * 进行文件保存
    	 * @param photoFile	上传上来的图片文件对象
    	 * @param Filename	上传图片文件名
    	 * @param FileUploadDir	 上传图片文件名路径
    	 * @param request	上传图片的目前请求
    	 * @return	返回是否上传成功
    	 */
    	public boolean saveFile(MultipartFile photoFile,String Filename,HttpServletRequest request){
    		if (!photoFile.isEmpty()) {
    			String filePathString = request.getServletContext().getRealPath(this.getFileUploadDir()) + Filename;
    			try {
    				return UploadFileUtil.save(photoFile.getInputStream(), new File(filePathString));
    			} catch (Exception e) {
    				e.printStackTrace();
    				return false;
    			}
    		}else {
    			return false;
    		}	
    	}
    	
    	public abstract String getFileUploadDir();
    }
    

    6、编写上传文件的Action

    package cn.liang.action;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.log4j.Logger;
    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 cn.liang.util.action.AbstractAction;
    
    @Controller
    @RequestMapping("/pages/file/*") 
    public class FileAction extends AbstractAction {
    	private Logger log = Logger.getLogger(FileAction.class) ;
    	
    	@RequestMapping("addFile")
    	public ModelAndView addFile(MultipartFile photoFile,HttpServletRequest request){
    		log.info("*** 文件原始名称:" + photoFile.getOriginalFilename());
    		log.info("*** 文件是否上传:" + photoFile.isEmpty());
    		log.info("*** 文件大小:" + photoFile.getSize());
    		log.info("*** 文件类型:" + photoFile.getContentType());
    		String fileName = super.createFileName(photoFile) ;
    		log.info("*** 文件名:" + fileName);
    		log.info("*** 上传结果:" + super.saveFile(photoFile, fileName,request)); 
    		return null;
    	}
    
    	@Override
    	public String getFileUploadDir() {
    		return "/upload/images/";
    	}	
    }
    

    7、编写上传文件的JSP:/pages/addFile.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Upload Photo</title>
    </head>
    <body>
    <%
    	String addUrl = request.getContextPath() + "/pages/file/addFile.action" ;
    %>
    <form action="<%=addUrl%>" method="post" enctype="multipart/form-data">
    	照片:<input type="file" name="photoFile" id="photoFile"><br>
    	<input type="submit" value="提交">
    </form>
    </body>
    </html>
    

    8、测试连接

    http://localhost:8080/springdemo/pages/addFile.jsp
    

    9、输出结果

    2018-12-10 14:40:08,517 INFO [cn.liang.action.FileAction] - *** 文件原始名称:pxe.png
    2018-12-10 14:40:08,517 INFO [cn.liang.action.FileAction] - *** 文件是否上传:false
    2018-12-10 14:40:08,518 INFO [cn.liang.action.FileAction] - *** 文件大小:284974
    2018-12-10 14:40:08,518 INFO [cn.liang.action.FileAction] - *** 文件类型:image/png
    2018-12-10 14:40:08,519 INFO [cn.liang.action.FileAction] - *** 文件名:49f7c05d-97e2-4314-954c-80b817cb8021.png
    2018-12-10 14:40:08,525 INFO [cn.liang.action.FileAction] - *** 上传结果:true
    
  • 相关阅读:
    JVM理解
    ubuntu下Android反编译详细教程-apktool,dex2jar,jd-gui的使用
    Add Two Numbers
    Two Sum
    JS实现总价随数量变化而变化(顾客购买商品表单)
    族谱管理系统(孩子兄弟存储结构)
    Java登录界面的实现(注册、登录、背景图片)
    Java GUI记账本(基于Mysql&&文件存储两种版本)
    几种对栈操作的方法
    Java中的成员内部类
  • 原文地址:https://www.cnblogs.com/liangjingfu/p/10106668.html
Copyright © 2020-2023  润新知