zoukankan      html  css  js  c++  java
  • Spring MVC实现文件上传

    基础准备:


    Spring MVC为文件上传提供了直接支持,这种支持来自于MultipartResolver。Spring使用Jakarta Commons FileUpload技术实现了一个MultipartResolver:CommonsMultipartResolver。

    Spring MVC上下文中默认没有装配MultipartResolver,因此我们需要配置它。

        <!-- 文件上传 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="UTF-8"></property>
            <property name="maxUploadSize" value="52428800"></property>
            <property name="uploadTempDir" value="temp"></property>
        </bean>

    上面设置了文件编码为"UTF-8",设置了最大上传大小为50M,设置了上传文件的临时目录为Web目录下的temp。

    控制器:


    有了MultipartResolver,就可以在Controller中使用文件上传功能了。Spring MVC将上传文件绑定到MultipartFile对象上。MultipartFile提供了获取上传文件内容、文件名等内容,通过其transferTo()方法可以将文件储存到硬盘中:

        /**
         * @描述 文件上传演示操作
         * @时间 2013-7-26 下午5:17:42
    */
        @ResponseBody
        @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
        public String doFileUpload(@RequestParam String desc, @RequestParam MultipartFile file)
                throws IllegalStateException, IOException {
            if (!file.isEmpty()) {
                String path = ProjectUtil.getMavenWebProjectPath() + "runtime";
                ProjectUtil.createDir(path);
                file.transferTo(new File(path + "/" + file.getOriginalFilename()));
            } else {
                return "fail";
            }
            return SUCCESS;
        }

    这里使用了工具类中(ProjectUtil)的两个方法:

        /**
         * @描述 Maven项目中,获取项目路径
         * @时间 2013-7-26 下午5:13:02
         * @return 项目路径。如:D:kuaipanspringmvc
         */
        public static String getMavenWebProjectPath() {
            Resource resource = new ClassPathResource("./");
            String filePath = "";
            try {
                filePath = resource.getFile().getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
            filePath = filePath.substring(0, filePath.indexOf("target"));
            return filePath;
        }
        /**
         * 创建目录
         */
        public static void createDir(String filePath) {
            File myFile = new File(filePath);
            if (!myFile.exists()) {
                myFile.mkdirs();
            }
        }

    页面:


     页面上,就是一个表单,然后一个文件字段和描述字段。需要注意的是<form>上要有enctype="multipart/form-data"属性定义。

  • 相关阅读:
    Shiro(三):Spring-boot如何集成Shiro(下)
    Shiro(二):Spring-boot如何集成Shiro(上)
    Shiro踩坑记(一):关于shiro-spring-boot-web-starter自动注解无法注入authorizer的问题
    Shiro(一):Shiro介绍及主要流程
    Netty(七):EventLoop学习前导——Reactor模式
    java基础
    nginx,tomcat,apache三者分别用来做什么,有何区别
    python之yagmail发送邮件
    python之文件的读写
    python之字符串方法
  • 原文地址:https://www.cnblogs.com/china-li/p/3225389.html
Copyright © 2011-2022 走看看