SpringMVC(三)—>文件上传和下载

一、文件上传(方式一)

  前端表单要求:为了能上传文件,必须将表单的 method 设置为 POST,并将 enctype 设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;一旦设置了enctype为multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据。
  Spring MVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。Spring MVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类: CommonsMultipartResolver。因此 SpringMVC 的文件上传还需要依赖 Apache Commons FileUpload的组件。

1、springmvc-servlet.xml 配置文件如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.lxc.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--ID必须为multipartResolver,否则就400问题-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="1048576"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>

</beans>

这个bena的id必须为:multipartResolver ,非常之重要,我的老师就在这栽过坑!!!

2、前端的表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>

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

</body>
</html>

3、导入上传文件的 jar 包 commons-fileupload

Maven 会自动帮我们导入它的依赖包 commons-io

<!--文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>

我们会使用它的实现类 CommonsMultipartFile , 常用方法如下:

方法说明
String getOriginalFilename()获取上传文件的原名
InputStream 、getInputStream()获取文件流
void transferTo(File dest)将上传文件保存到一个目录文件中
4、Controller 类的编写

注:必须加上 @RequestParam , 否则也会报错!作用是用来实现封装!

package com.lxc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class FileUploadController {

    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //上传文件名称
        String filename = file.getOriginalFilename();
        if ("".equals(filename)) {
            return "redirect:/index.jsp";
        }
        System.out.println("文件上传名称" + filename);
        //上传保存路径
        String path = request.getServletContext().getRealPath("/upload");
        File realpath = new File(path);
        if (!realpath.exists()) {
            realpath.mkdirs();
        }
        System.out.println("上传文件保存地址" + realpath);
        InputStream inputStream = file.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(new File(realpath, filename));
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
        return "redirect:/index.jsp";
    }
}

二、文件上传(方式二)

方式二是采用 file.Transto 来上传,我们只需要改动 Controller 类即可

    /*
     * 采用file.Transto 来保存上传的文件
     */
    @RequestMapping("/upload2")
    public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件保存地址:"+realPath);

        //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
        file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));

        return "redirect:/index.jsp";
    }

三、文件下载

文件下载步骤:

  • 设置 response 响应头
  • 读取文件 – InputStream
  • 写出文件 – OutputStream
  • 执行操作
  • 关闭流 (先开后关)
1、Controller 类的编写
//文件下载
    @RequestMapping(value = "/download")
    public String downLoad(HttpServletResponse response) throws IOException {
         //图片的路径
        String path = "C:\\Users\\lenovo\\Desktop\\";
        // 图片的名字
        String filename = "picture.jpg";
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");//二进制流传输数据
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

        File file = new File(path, filename);
        FileInputStream inputStream = new FileInputStream(file);

        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];

        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
            outputStream.flush();
        }

        outputStream.close();
        inputStream.close();

        return null;

    }
2、前端代码

前端代码就是一个简单的链接

<a href="/download">点击下载</a>

进行测试,图片可以正常下载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Spring MVC来说,文件上传下载是常见的功能之一。下面是关于如何实现文件上传下载的基本步骤: 1. 文件上传: - 在Spring MVC的配置文件中,添加`CommonsMultipartResolver`来解析文件上传请求。 - 创建一个表单页面,使用`enctype="multipart/form-data"`属性,确保可以上传文件。 - 在Controller中创建一个处理文件上传请求的方法,使用`@RequestParam("file") MultipartFile file`注解来接收文件。 - 在方法内部,可以通过`file.getInputStream()`来获取文件的输入,进而实现上传操作。 2. 文件下载: - 在Controller中创建一个处理文件下载请求的方法。 - 在方法内部,使用`HttpServletResponse`对象设置响应头信息,包括`Content-Disposition`和`Content-Type`。 - 通过`response.getOutputStream()`获取输出,并将文件的内容写入输出。 需要注意的是,为了确保文件上传下载的安全性,可以进行一些额外的处理,例如限制文件类型、大小等。 以下是一个示例代码,用于演示文件上传下载: ```java @Controller public class FileController { @Autowired private ServletContext servletContext; @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file) { try { String fileName = file.getOriginalFilename(); String filePath = servletContext.getRealPath("/uploads/") + fileName; file.transferTo(new File(filePath)); return "redirect:/success"; } catch (Exception e) { e.printStackTrace(); return "redirect:/error"; } } @RequestMapping(value = "/download", method = RequestMethod.GET) public void download(HttpServletResponse response) { try { String fileName = "example.txt"; String filePath = servletContext.getRealPath("/downloads/") + fileName; File file = new File(filePath); InputStream inputStream = new FileInputStream(file); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentType("application/octet-stream"); IOUtils.copy(inputStream, response.getOutputStream()); response.flushBuffer(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码中,`servletContext.getRealPath()`方法用于获取文件的实际路径,`IOUtils.copy()`方法用于将文件内容写入输出。 请注意,上述示例仅为演示目的,实际应用中可能需要进行更多的异常处理、文件校验等操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值