SpringMVC实现文件上传

1.首先需要导包

<!-- commons-io和commons-fileupload -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
</dependency>

2.配置multipart (file upload) support

bean的id名必须是multipartResolver,否则会无效

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="10485760000"/>
        <property name="maxInMemorySize" value="40960"/>
</bean>

3.upload.jsp页面

    <!-- form要设置为post提交,并且要设置数据编码要enctype="multipart/form-data" -->
    <form action="upload.do" method="post" enctype="multipart/form-data">
        <input type="file" name="file" text=""/>
        <input type="submit" value="提交">
    </form>

4.编写Conroller.java

@Controller
public class FileUploadController {

    //需设置为post方式:method = RequestMethod.POST
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    //参数CommonsMultipartFile file前必须加@RequestParam("file"),并且名字需和form提交的相同
    public String upload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest req) throws IOException{
        
        //1.io传统流方式        
        //存储路径
        /*String path = req.getRealPath("/fileupload");
        
        
        InputStream is = file.getInputStream();
        
        FileOutputStream os = new FileOutputStream(new File(path,file.getOriginalFilename()));
        
        int len = 0;
        byte[] buffer = new byte[1024];
        while((len=is.read(buffer))>0){
            os.write(buffer,0,len);
        }
        os.close();
        is.close();*/

        //2.spring提供的CommonsMultipartFile自带方法,此方式更快
        String path = req.getServletContext().getRealPath("/fileupload")+"/"+file.getOriginalFilename();
        
        file.transferTo(new File(path));
        
        return "success.jsp";
    }
}
原文地址:https://www.cnblogs.com/xiaohongxin/p/6523254.html