zoukankan      html  css  js  c++  java
  • 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";
        }
    }
  • 相关阅读:
    2019年Pycharm最新激活码_学生党适用
    Day14_分享昨天看到的一句话
    监督学习算法_k-近邻(kNN)分类算法_源代码
    Python学习需要安装的工具
    Python基础学习资料推荐
    总结一下公司项目使用各种较新的前端技术和 Api 的一些经验。
    由 Session 和 Cookie 的区别说起
    我理解的正确的代码
    回忆我是如何赢得一次踢毽子比赛
    日常的例子说明 throttle 和 debounce 的区别
  • 原文地址:https://www.cnblogs.com/xiaohongxin/p/6523254.html
Copyright © 2011-2022 走看看