zoukankan      html  css  js  c++  java
  • 使用springmvc实现文件上传

    该配置在javaweb上传文件篇中的基础上进行配置:https://www.cnblogs.com/flypig666/p/11745182.html

    1、配置文件解析器,在springmvc.xml中进行配置

        <!-- 配置文件解析器,id必须为multipartResolver-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="maxUploadSize" value="10485760" />
        </bean>

    2、编写jsp

        <h3>springmvc:文件上传</h3>
        <form action="file/upload2" method="post" enctype="multipart/form-data">
            选择文件:<input type="file" name="upload2" /><br/>
            <input type="submit" value="上传" />
        </form>

    3、编写controller

        /**
         * SpringMVC文件上传
         * @param request
         * @return
         * @throws Exception
         * MultipartFile upload2: upload2为提交文件按钮的name值,表示文件上传项
         */
        @RequestMapping("/upload2")
        public String fileupload1(HttpServletRequest request, MultipartFile upload2) throws Exception {
            System.out.println("springmvc文件上传");
    
            // 使用fileupload组件完成组件上传
            // 上传的位置
            // request.getSession().getServletContext():拿到最大的域对象,getRealPath():拿到某路径下的绝对路径
            String path = request.getSession().getServletContext().getRealPath("/uploads/");
            // 判断该路径是否存在
            File file = new File(path);
            if (!file.exists()){
                // 创建文件夹
                file.mkdirs();
            }
    
            // springmvc不需要自己解析request
            // 获取上传文件名
            String filename = upload2.getOriginalFilename();
            // 把文件的名称设置为唯一值,uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid + "_" + filename;
            // 完成文件上传
            upload2.transferTo(new File(file,filename));
    
            return "success";
        }
  • 相关阅读:
    __doPostBack的使用
    【转】function,new,constructor and prototye
    谈谈一些网页游戏失败的原因到底有哪些?(转)
    全面剖析页游巨头发家史(转)
    2013.02.20开通博客
    老子喜欢的女人
    如何成为强大的程序员?(转)
    注重健康
    学习方法总结
    数据库知识点滴积累
  • 原文地址:https://www.cnblogs.com/flypig666/p/11745249.html
Copyright © 2011-2022 走看看