SpringMVC实现文件的上传和下载

1、文件上传

1.1 导入依赖

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
	
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

1.2 设置文件上传解析器

bean的名字是固定的:multipartResolver

<!--配置文件上传解析器   id必须是multipartResolver-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--设置文件大小的上限 1Mb-->
        <property name="maxUploadSize" value="#{1024*1024}"/>
    </bean>

1.3 jsp页面

<fieldset>
    <legend>文件上传</legend>
    <%--必须设置 表单的提交类型:"multipart/form-data"--%>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="submit" value="提交">
    </form>
</fieldset>

1.4 新建文件上传的Controller类

@Controller
public class UploadFile {
    /*文件上传*/
    @Autowired
    private ServletContext servletContext;

    @RequestMapping("/upload")
    public ModelAndView file(String filename, MultipartFile file) throws Exception{
        /*把文件对象以流形式,写入到目标文件夹中(只能保存到target文件夹中)*/
        String realPath = servletContext.getRealPath("/");
        /*自定义保存文件的文件名*/
        String path = realPath + new Date().getTime() + file.getOriginalFilename();
        /*加载*/
        File newfile = new File(path);
        /*执行*/
        file.transferTo(newfile);
        return null;
    }
}

2、文件下载

2.1 jsp页面

<fieldset>
    <legend>文件下载</legend>
    <form action="/download" method="post">
        输入要下载的文件名<input name="filename"/><br/>
        <input type="submit" value="提交">
    </form>
</fieldset>

2.2 新建文件下载的Controller类


@Controller
public class DownloadFile {
    /*文件下载*/
    @Autowired
    private ServletContext context;

    @RequestMapping("/download")
    public ModelAndView download(String filename, HttpServletResponse response) throws Exception{

        /*设置文件下载的响应头*/
        response.setContentType("application/x-msdownload");

        response.setHeader("Content-Disposition","attachment;filename="+filename);


        //设置图片所在路径
        String realpath = context.getRealPath("/");
        //执行
        Files.copy(Paths.get(realpath,filename),response.getOutputStream());

        return null;
    }

}


3、注意:

1.SpringMVC上传必须配置文件上传解析器"org.springframework.web.multipart.commons.CommonsMultipartResolver",解析器的id必须为"multipartResolver"
2.做文件上传的form表单的提交方式必须为"post",同时表单的提交类型为:“multipart/form-data”
3.控制器的方法可以使用MultipartFile对象,接收上传的文件
4.SpringMVC没有对文件的下载做封装

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Spring MVC的文件上传下载功能,需要进行以下步骤: 1、引入Apache Commons FileUpload组件的依赖。在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> ``` 2、配置文件上传解析器。在Spring MVC的配置文件中,配置一个MultipartResolver的Bean用于处理文件上传请求。 3、创建文件上传的表单。在HTML表单中,设置enctype为"multipart/form-data",并添加一个文件选择框。 4、创建文件上传的控制器。在控制器中,使用MultipartFile参数接收上传文件,并执行相应的操作,比如保存文件到指定位置。 5、创建文件下载的控制器。在控制器中,使用ResponseEntity<byte[]>对象来实现文件下载,设置相应的响应头信息,如Content-Disposition和文件名。 下面是一个示例的代码,演示了如何实现文件上传下载: ``` // 文件上传的控制器 @Controller public class FileUploadController { @RequestMapping("/fileUpload") public String testFileUpload(MultipartFile photo, HttpSession session) throws IOException { String filename = photo.getOriginalFilename(); ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("photo"); File file = new File(realPath); if (!file.exists()) { file.mkdir(); } String finalPath = realPath + File.separator + filename; photo.transferTo(new File(finalPath)); return "success"; } } // 文件下载的控制器 @Controller public class FileDownloadController { @RequestMapping("/fileDownload") public ResponseEntity<byte[]> testFileDownload(HttpSession session) throws IOException { ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("static/img/a.jpg"); InputStream inputStream = new FileInputStream(realPath); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=a.jpg"); HttpStatus status = HttpStatus.OK; ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status); inputStream.close(); return responseEntity; } } // 文件上传的表单 <form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="photo" multiple> <input type="submit" value="上传"/> </form> ``` 通过以上步骤,你可以在Spring MVC中实现文件上传下载功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值