欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring MVC中上传文件实例

程序员文章站 2023-01-29 10:28:44
springmvc(注解)上传文件需要注意的几个地方: 1、form的enctype="multipart/form-data",这个是上传文件必须的 2、applic...

springmvc(注解)上传文件需要注意的几个地方:
1、form的enctype="multipart/form-data",这个是上传文件必须的
2、applicationcontext.xml配置:

复制代码 代码如下:

<!-- springmvc上传文件时,需要配置multipartresolver处理器 -->
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
    <property name="defaultencoding" value="utf-8"/>
    <!-- 指定所上传文件的总大小不能超过200kb。注意maxuploadsize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
    <property name="maxuploadsize" value="200000"/>
    <!-- 最大内存大小 (10240)-->
    <property name="maxinmemorysize" value="40960" />
</bean>
  
<!-- springmvc在超出上传文件限制时,会抛出org.springframework.web.multipart.maxuploadsizeexceededexception -->
<!-- 该异常是springmvc在检查上传的文件信息时抛出来的,而且此时还没有进入到controller方法中 -->
<bean id="exceptionresolver" class="org.springframework.web.servlet.handler.simplemappingexceptionresolver">
    <property name="exceptionmappings">
        <props>
            <!-- 遇到maxuploadsizeexceededexception异常时,自动跳转到/web-inf/jsp/error_fileupload.jsp页面 -->
            <prop key="org.springframework.web.multipart.maxuploadsizeexceededexception">error_fileupload</prop>
        </props>
    </property>
</bean>

用于上传的表单页面/web-inf/jsp/upload.jsp

复制代码 代码如下:

<%@ page language="java" contenttype="text/html; charset=utf-8"
    pageencoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
    <head>
        <script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <title>上传图片</title>
    </head>
    <body>
        <form action="<%=request.getcontextpath()%>/upload/filesupload" method="post" enctype="multipart/form-data">
            yourfile: <input type="file" name="myfiles"/><br/>
            yourfile: <input type="file" name="myfiles"/><br/>
            <input type="submit" value="上传图片"/>
        </form>
    </body>
</html>

上传文件内容过大时的提示页面/web-inf/jsp/error_fileupload.jsp

复制代码 代码如下:

<%@ page language="java" pageencoding="utf-8"%>
<h1>文件过大,请重新选择</h1>

上传文件的核心uploadcontroller类

复制代码 代码如下:

package com.ljq.web.controller.annotation;
 
import java.io.file;
 
import javax.servlet.http.httpservletrequest;
 
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.multipart.multipartfile;
 
/**
 * 上传图片
 *
 * @author administrator
 *
 */
@controller
@requestmapping("/upload")
public class uploadcontroller {
 
    @requestmapping("/toupload")
    public string toupload() {
        return "/upload";
    }
 
    /***
     * 保存文件
     *
     * @param file
     * @return
     */
    private boolean savefile(httpservletrequest request, multipartfile file) {
        // 判断文件是否为空
        if (!file.isempty()) {
            try {
                // 保存的文件路径(如果用的是tomcat服务器,文件会上传到\\%tomcat_home%\\webapps\\yourwebproject\\upload\\文件夹中  )
                string filepath = request.getsession().getservletcontext()
                    .getrealpath("/") + "upload/" + file.getoriginalfilename();
                file savedir = new file(filepath);
                if (!savedir.getparentfile().exists())
                    savedir.getparentfile().mkdirs();
                
                // 转存文件
                file.transferto(savedir);
                return true;
            } catch (exception e) {
                e.printstacktrace();
            }
        }
        return false;
    }
 
    /**
     * 上传图片
     *
     * @param files
     * @param request
     * @return
     */
    @requestmapping("/filesupload")
    public string filesupload(@requestparam("myfiles") multipartfile[] files,
            httpservletrequest request) {
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                multipartfile file = files[i];
                // 保存文件
                savefile(request, file);
            }
        }
        
        // 重定向
        return "redirect:/upload/toupload";
    }
 
}

到此文件上传开发就结束了。

multipartfile类常用的一些方法:
string getcontenttype() //获取文件mime类型
inputstream getinputstream() //返回文件流
string getname() //获取表单中文件组件的名字
string getoriginalfilename() //获取上传文件的原名
long getsize() //获取文件的字节大小,单位byte
boolean isempty() //是否为空
void transferto(file dest) //保存到一个目标文件中