SpringMVC文件上传配置——单文件上传

1.导入相关jar包

    这里我们用的是:commons-io-2.4.jar、commons-fileupload-1.2.2.jar、commons-lang-2.6.jar

2.首先配置springmvc-servlet.xml(共同点):无论多文件还是单文件都要配置

	
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="500000" />   
		<property name="defaultEncoding" value="UTF-8" />
		<property name="resolveLazily" value="true" />
        </bean>

    在CommonsMultipartResolver中呢有几个关键的属性:

    defaultEncoding:请求编码格式 默认为ISO-8859-1

    maxUploadSize:上传文件大小上限:这里我设置的是500KB

    resolveLazily:延迟文件解析

    uploadTempDir:上传文件的临时路径

     3 .编写控制器:

         @RequestMapping(value="saveFile.html",method=RequestMethod.POST)    
         public void saveFile(@RequestParam("file") MultipartFile file,HttpServletRequest request){
            //判断文件是否为空
             if( !file.isEmpty()){
                 // 文件存放路径
                String path = request.getServletContext().getRealPath("/");
                // 文件名称
                String name = String.valueOf(new Date().getTime()+"_"+file.getOriginalFilename());
                File destFile = new File(path,name);
                // 转存文件
                try {
                    file.transferTo(destFile);
                } catch (IllegalStateException | IOException e) {
                    e.printStackTrace();
                }
                return "index";
            }
        }

    4.编写测试的JSP(save.jsp和index.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>上传单个文件示例</title>
        <link rel="stylesheet" href="<%=request.getContextPath()%>/statics/css/save.css" type="text/css" />
    </head>
    <body>
          <div align="center">
                <from action="<%=request.getContextPath()%>/saveFile.html" method="post" enctype="multipart/form-data">
                    <input type="file" name="file"/>
                    <button type="submit" >提交</button>
                </form>
         </div>
    </body>
</html>

    

扫描二维码关注公众号,回复: 3234856 查看本文章
<%@ 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>上传成功</title>
        <link rel="stylesheet" href="<%=request.getContextPath()%>/statics/css/save.css" type="text/css" />
    </head>
    <body>
         <h1>上传成功</h1>
    </body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_41706675/article/details/80974265