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

转载于:https://www.cnblogs.com/liangjingfu/p/10106668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值