Spring MVC实现文件上传

本文介绍了如何在SpringMVC中实现文件上传功能,包括配置MultipartResolver、使用MultipartFile对象处理上传文件,并展示了具体的代码实现。

基础准备:


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:\kuaipan\springmvc\
     */
    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"属性定义。

 

 

转载于:https://www.cnblogs.com/china-li/p/3225389.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值