springMvc7 - 文件上传、下载

来源:https://www.bilibili.com/video/BV1GE411d7KE?p=8

上一节:https://blog.csdn.net/qq_40893824/article/details/107282922
下一节:https://blog.csdn.net/qq_40893824/article/details/107298855

单文件上传

pom.xml
springmvc.xml
web.xml
FileHandler
upload.jsp

1 pom 文件中,添加代码:

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3</version>
    </dependency>

2 resources/ springmvc.xml 中,添加代码:

    <!--  配置上传组件  -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>

3 WEB-INF/ web.xml 中,添加代码:

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.png</url-pattern>
  </servlet-mapping>

表示 png 的图片可以上传

4 controller 中,新建 实现类 FileHandler,加入代码:

package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class FileHandler {

    @PostMapping("/upload")
    public String upload(MultipartFile img, HttpServletRequest request){
        if(img.getSize()>0){
            // 获取路径
            String path = request.getServletContext().getRealPath("file");

            // 获取文件名
            String name = img.getOriginalFilename();

            File file = new File(path,name);
            try {
                img.transferTo(file);
                // 保存文件上传后的文件路径
                request.setAttribute("path", "/file/"+name);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return "upload";
    }
}

其中 String path = request.getServletContext().getRealPath("file");
是在 tomcat 中叫 ‘file’ 的文件夹

5 webapp 中,新建 upload.jsp,加入代码:
<%@ page isELIgnored="false" %>

    <form action="/file/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="img" />
        <input type="submit" value="上传"/>
    </form>
    <img src="${path}">

input 的 type 设置为 file。
form 的 method 设置为 post(get 请求只能将文件名传给服务器)
from 的 enctype 设置为 multipart-form-data(如果不设置只能将文件名传给服务器)

6 RestHandler 中,修改端口:

7 启动 tomcat,在 tomcat-9.0.36\webapps\ROOT 中,新建 file 的文件夹(必须

进入 http://localhost:8080/upload.jsp

多文件上传

遍历数组 来传文件

FileHandler
pom.xml
uploads.jsp

1 FileHandler 中,添加代码:

    @PostMapping("/uploads")
    public String uploads(MultipartFile[] imgs,HttpServletRequest request){
        List<String> files = new ArrayList<>();
        for(MultipartFile img:imgs){
            if(img.getSize()>0){
                // 获取路径
                String path = request.getServletContext().getRealPath("file");

                // 获取上传文件名
                String name = img.getOriginalFilename();

                File file = new File(path,name);
                try {
                    img.transferTo(file);
                    files.add("/file/" + name);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        request.setAttribute("files",files);
        return "uploads";
    }

2 pom.xml 中,添加代码:

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

3 webapp 中,新建 uploads.jsp,加入代码:

<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<form action="/file/uploads" method="post" enctype="multipart/form-data">
        file1:<input type="file" name="imgs"/><br/>
        file2:<input type="file" name="imgs"/><br/>
        file3:<input type="file" name="imgs"/><br/>
        <input type="submit" value="上传">
    </form>
    <c:forEach items="${files}" var="file">
        <img src="${file}" width="300px">
    </c:forEach>
这里对应 pom 新加的依赖

4 启动 tomcat,在 tomcat-9.0.36\webapps\ROOT 中,新建 file 的文件夹(必须

进入 http://localhost:8080/uploads.jsp

下载

上传:客户端消息 传到 服务端
下载:服务端消息 传到 客户端

FileHandler
download.jsp

1 FileHandler 中,添加代码:

    @GetMapping("/download/{name}")
    public void download(@PathVariable("name") String name,
                         HttpServletRequest request,
                         HttpServletResponse response){
        if(name != null){
            name += ".png";
            // 获取路径
            String path = request.getServletContext().getRealPath("file");

            File file = new File(path,name);
            OutputStream outputStream = null;
            if(file.exists()){
                // 下载设置
                response.setContentType("application/forc-download");
                // 下载后的文件名字
                response.setHeader("Content-Disposition", "attachment;filename = " + name );

                try {
                    outputStream = response.getOutputStream();

                    // FileUtils:文件 转 Byte型数组
                    outputStream.write(FileUtils.readFileToByteArray(file));
                    outputStream.flush();
                }catch (IOException e){
                    e.printStackTrace();
                }finally {
                    if(outputStream != null){
                        try {
                            outputStream.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

2 webapp 中,新建 download.jsp

    <a href="/file/download/1">1.png</a>
    <a href="/file/download/2">2.png</a>
    <a href="/file/download/3">3.png</a>

3 启动 tomcat,在 tomcat-9.0.36\webapps\ROOT 中,新建 file 的文件夹(必须

先上传
进入 http://localhost:8080/uploads.jsp

下载:
进入 http://localhost:8080/download.jsp

上一节:https://blog.csdn.net/qq_40893824/article/details/107282922
下一节:https://blog.csdn.net/qq_40893824/article/details/107298855

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_1403034144

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值