SpringMVC实战(八)——文件上传与下载

本文介绍如何在SpringMVC框架中实现文件上传和下载功能。上传时需配置MultipartResolver并处理MultipartFile对象,下载则利用ResponseEntity定义HTTP响应头。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

该文章基于《Spring+MyBatis企业应用实战》进行总结,旨在积累巩固

文件上传

文件的上传需要在页面中设置enctype为multipart/form-data,method为post,如下所示:

<form action="XXX" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit"/>
</form>

当传入了文件之后还需要再Controller中进行文件的获取以及处理:

@Controller
public class XXController{
    @RequestMapping("XXX")
    public XXX getFile(@RequestParam("file") MultipartFile file){
        file.transferTo(new File("你想要存储的位置"));
    }
}

Spring MVC中并没有提供MultipartResolver,因此需要在上下文中配置MultipartResolver:

<bean class="一般使用org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize">
        <value>XXX</value>
    </property>
    <property name="defaultEncoding">
        <value>UTF-8</value>
    </property>
</bean>

所以需要引入额外的JAR包,一般使用Commons FileUpload组件

文件下载

文件的下载相对简单,会用到SpringMVC提供的ResponseEntity类型,该类型可以方便的进行定义返回的HttpHeaders和HttpStatus,文件的下载还是需要用Controller进行处理

@Controller
public class XXXController{
    @RequestMapping("/download")
    public ReponseEntity<byte[]> download(){
        HttpHeanders headers = new HttpHeaders();
        //通知浏览器以attachment方式进行文件下载
        headers.setContentDispositionFormData("attachment","下载文件名");
        herders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //FileUtils是Commons FileUpload的组件
        return new ReponseEntity<byte[]>(FileUtils.readFileToByteArray(new File("下载文件绝对路径")),headers,Httpstatus.CREATED)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值