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";
        }
  • 相关阅读:
    HttpClient Coder Example
    HttpClient容易忽视的细节—连接关闭
    Hibernate中所有包作用详细讲解
    Commons-VFS 使用SFTP
    Ant 编译项目资源不足
    ActiveMQ介绍和ActiveMQ入门实例
    ActiveMQ与MSMQ的异同
    linux nohup命令详解
    linux sed命令详解
    linux iptables命令详解
  • 原文地址:https://www.cnblogs.com/flypig666/p/11745249.html
Copyright © 2011-2022 走看看