SpringMVC_4_实操FileUpload

previous:SpringMVC_3_实操Binding next:SpringMVC_5_实操JSON

http://www.imooc.com/video/8413

4-6 FileUpload 单文件上传

mvc-dispatcher-servlet.xml中加入如下代码

    <!--200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="209715200" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="resolveLazily" value="true" />
    </bean>

org.springframework.web.multipart.commons.CommonsMultipartResolver

pom.xml中引入

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

 如下图所示commons-fileupload又依赖于commons-io包,这样在编码中就不用显示的引入了。

2. 引入之后在contoller中:

 

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public String showUploadPage(@RequestParam(value= "multi", required = false) Boolean multi){    
        if(multi != null && multi){
            return "course_admin/multifile";    
        }
        return "course_admin/file";        
    }
    

 

 

JSP:

<form method="post" action="/courses/doUpload" enctype="multipart/form-data">

文件上传时必须显示指定的属性,如果没有无法完成工作。

<%@ 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()%>/resources/css/main.css" type="text/css" />
</head>
<body>
<div align="center">

<h1>上传附件</h1>
<form method="post" action="/courses/doUpload" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</div>
</body>
</html>

controller,doUploadFile方法

1)文件上传期待是post方式

2)MultipartFile类,是上传文件的接口

3)@RequestParam("file")使之与表单文件相关联

4) 把文件拷贝到指定位置

  a.输入流:file.getInputStream()

  b.保存位置和保存名指定:new File("c:\\temp\\imooc\\", System.currentTimeMillis()+ file.getOriginalFilename()));

  c.System.currentTimeMillis()为时间戳

  FileUtils.copyInputStreamToFile(file.getInputStream(), new File("c:\\temp\\imooc\\", System.currentTimeMillis()+ file.getOriginalFilename()));

5)返回页,前后文已经通过配置设定,只指定JSP的名字即可。

  return "success"; 

    @RequestMapping(value="/doUpload", method=RequestMethod.POST)
    public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException{
        
        if(!file.isEmpty()){
            log.debug("Process file: {}", file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File("c:\\temp\\imooc\\", System.currentTimeMillis()+ file.getOriginalFilename()));
        }
        
        return "success";
    }

 

posted @ 2017-04-24 10:45  charles999  阅读(221)  评论(0编辑  收藏  举报