• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

SpringBoot文件上传下载

武飞扬头像
WinnerBear
帮助1

目录

1、单文件上传

2、多文件上传

3、下载、在线查看

4、上传文件大小限制

5、自定义上传文件超过限制异常


1、单文件上传

这里的enctype的类型是mulitpart/form-data

两种形式的提交,一种是以form表单的形式,一个是ajax的形式

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>上传文件</title>
  6.  
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  7.  
    </head>
  8.  
    <body>
  9.  
    <!--form表单形式上传-->
  10.  
    <form action="/upload" method="post" enctype="multipart/form-data">
  11.  
    <input type="file" name="multipartFile" id="file" value="上传文件">
  12.  
    <input type="button" value="ajax形式上传" id="btn" onclick="onUpload()">
  13.  
    <input type="submit" value="form表单的submit上传">
  14.  
    </form>
  15.  
     
  16.  
    <script>
  17.  
    //var onUpload = function(){}
  18.  
    //ajax形式上传
  19.  
    function onUpload() {
  20.  
    //$("#multipartFile")[0]表示获取到js对象,files[0]表示获取到上传文件的第一个
  21.  
    var file = $("#file")[0].files[0];
  22.  
    var formData = new FormData(); //这个对象是可以让我们模拟form表单的提交
  23.  
    formData.append("multipartFile", file);
  24.  
    formData.append("isOnline", 1);
  25.  
    $.ajax({
  26.  
    type: "POST",
  27.  
    url: "/upload",
  28.  
    data: formData,
  29.  
    processData: false, //这里设置为false表示不让ajax帮我们把文件转换为对象格式,这里必须设置为false
  30.  
    contentType: false, //这里也要设置为false,不设置可能会出问题
  31.  
    success: function (msg) {
  32.  
    alert("上传文件成功");
  33.  
    }
  34.  
    })
  35.  
    }
  36.  
    </script>
  37.  
    </body>
  38.  
    </html>
学新通

我们将上传的文件放入到resources下面

这里不能使用request.getServletContext().getRealPath(""),因为这里获取到的路径是tomcat临时文件的目录

  1.  
    @PostMapping("upload")
  2.  
    @ResponseBody
  3.  
    //将上传的文件放在tomcat目录下面的file文件夹中
  4.  
    public String upload(MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
  5.  
    //获取到原文件全名
  6.  
    String originalFilename = multipartFile.getOriginalFilename();
  7.  
    // request.getServletContext()。getRealPath("")这里不能使用这个,这个是获取servlet的对象,并获取到的一个临时文件的路径,所以这里不能使用这个
  8.  
    //这里获取到我们项目的根目录,classpath下面
  9.  
    String realPath = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath();
  10.  
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  11.  
    String format = simpleDateFormat.format(new Date());
  12.  
    //文件夹路径,这里以时间作为目录
  13.  
    String path = realPath "static/" format;
  14.  
    //判断文件夹是否存在,存在就不需要重新创建,不存在就创建
  15.  
    File file = new File(path);
  16.  
    if (!file.exists()) {
  17.  
    file.mkdirs();
  18.  
    }
  19.  
     
  20.  
    //转换成对应的文件存储,new File第一个参数是目录的路径,第二个参数是文件的完整名字
  21.  
    multipartFile.transferTo(new File(file, originalFilename));
  22.  
     
  23.  
    //上传文件的全路径
  24.  
    String url = request.getScheme() "://" request.getServerName() ":" request.getServerPort() "/" format "/" originalFilename;
  25.  
    return url;
  26.  
     
  27.  
    }
学新通

2、多文件上传

多文件上传需要有multiple属性,我们也可以使用accept来利用前端来进行上传文件的指定

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>上传文件</title>
  6.  
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  7.  
    </head>
  8.  
    <body>
  9.  
     
  10.  
     
  11.  
    <form action="/upload1" method="post" enctype="multipart/form-data">
  12.  
    <input type="file" name="files" multiple value="多文件上传"> <!--accept可以指定上传文件类型,例如 accept="image/*"-->
  13.  
    <input type="submit" value="多文件上传">
  14.  
    </form>
  15.  
     
  16.  
    </script>
  17.  
    </body>
  18.  
    </html>
学新通

多文件的上传跟单文件其实差不多,就是对多文件遍历

  1.  
    @PostMapping("upload1")
  2.  
    @ResponseBody
  3.  
    //将上传的文件放在tomcat目录下面的file文件夹中
  4.  
    public String upload1(MultipartFile[] files, HttpServletRequest request, HttpServletResponse response) throws IOException {
  5.  
    List<String> list = new ArrayList<>();
  6.  
    //System.out.println(files.length);
  7.  
    for (MultipartFile multipartFile : files) {
  8.  
    //获取到文件全名
  9.  
    String originalFilename = multipartFile.getOriginalFilename();
  10.  
    // request.getServletContext()。getRealPath("")这里不能使用这个,这个是获取servlet的对象,并获取到的一个临时文件的路径,所以这里不能使用这个
  11.  
    //这里获取到我们项目的根目录,classpath下面
  12.  
    String realPath = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath();
  13.  
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  14.  
    String format = simpleDateFormat.format(new Date());
  15.  
    //文件夹路径,这里以时间作为目录
  16.  
    String path = realPath "static/" format;
  17.  
    //判断文件夹是否存在,存在就不需要重新创建,不存在就创建
  18.  
    File file = new File(path);
  19.  
    if (!file.exists()) {
  20.  
    file.mkdirs();
  21.  
    }
  22.  
     
  23.  
    //转换成对应的文件存储,new File第一个参数是目录的路径,第二个参数是文件的完整名字
  24.  
    multipartFile.transferTo(new File(file, originalFilename));
  25.  
     
  26.  
    //上传文件的全路径,一般是放在tomcat中
  27.  
    String url = request.getScheme() "://" request.getServerName() ":" request.getServerPort() "/" format "/" originalFilename;
  28.  
    //System.out.println("url=》》》》》" url);
  29.  
    list.add(url);
  30.  
    }
  31.  
    return new ObjectMapper().writeValueAsString(list);
  32.  
    }
学新通

3、下载、在线查看

进行文件下载的时候注意我们最好不要创建一个文件大小的数组来直接读取我们的文件,在文件过大的情况下,可能会导致内存溢出,可以根据实际情况,调整一次读取文件的大小,多次进行读取并输出

  1.  
    @RequestMapping("download")
  2.  
    public void download(HttpServletRequest request, HttpServletResponse response, String name, @RequestParam(defaultValue = "0") int isOnline) throws IOException {
  3.  
    try (ServletOutputStream outputStream = response.getOutputStream();) {
  4.  
    /*
  5.  
    这里要使用ResourceUtils来获取到我们项目的根目录
  6.  
    不能使用request.getServletContext().getRealPath("/"),这里获取的是临时文件的根目录(所以不能使用这个)
  7.  
    */
  8.  
    String path = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath();
  9.  
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  10.  
    String format = simpleDateFormat.format(new Date());
  11.  
    String realPath = path "static/" format "/" name;
  12.  
    File file = new File(realPath);
  13.  
    //如果下载的文件不存在
  14.  
    if (!file.exists()) {
  15.  
    response.setContentType("text/html;charset=utf-8");
  16.  
    //response.getWriter().write(str);这种写入的就相当于生成了jsp/html,返回html/jsp,所以需要我们进行contentType的设置
  17.  
    response.getWriter().write("下载的文件不存在");
  18.  
    return;
  19.  
    }
  20.  
     
  21.  
    InputStream in = new FileInputStream(realPath);
  22.  
    int read;
  23.  
     
  24.  
    //byte[] b = new byte[in.available()];创建一个输入流大小的字节数组,然后把输入流中所有的数据都写入到数组中
  25.  
    byte[] b = new byte[1024];
  26.  
    /*
  27.  
    1、Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
  28.  
    2、attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
  29.  
    3、filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
  30.  
    */
  31.  
    /* 注意:文件名字如果是中文会出现乱码:解决办法:
  32.  
    1、将name 替换为 new String(filename.getBytes(), "ISO8859-1");
  33.  
    2、将name 替换为 URLEncoder.encode(filename, "utf-8");
  34.  
    */
  35.  
    if (isOnline == 0) {
  36.  
    //在线打开
  37.  
    response.addHeader("Content-Disposition", "inline;filename=" URLEncoder.encode(name, "utf-8"));
  38.  
    } else {
  39.  
    //下载形式,一般跟application/octet-stream一起使用
  40.  
    response.addHeader("Content-Disposition", "attachment;filename=" URLEncoder.encode(name, "utf-8"));
  41.  
    //如果单纯写这个也可以进行下载功能,表示以二进制流的形式
  42.  
    response.setContentType("application/octet-stream");
  43.  
    }
  44.  
    //文件大小
  45.  
    response.addHeader("Content-Length", "" file.length());
  46.  
    while ((read = in.read(b)) > 0) {
  47.  
    outputStream.write(b);
  48.  
    }
  49.  
    } catch (Exception e) {
  50.  
    System.out.println(e.getMessage());
  51.  
    throw e;
  52.  
    }
  53.  
    }
学新通

4、上传文件大小限制

学新通

 默认的单文件大小是1m,多文件的总大小10m,超过就会报MaxUploadSizeExceededException异常

我们根据实际情况进行调整

例如

学新通

5、自定义上传文件超过限制异常

学新通

springboot自带的异常显示很多时候都不是我们自己想要的,那么对于这种异常,我们可以使用自定义异常来进行显示

  1.  
    package org.springframework.myspringboot.exception;
  2.  
     
  3.  
    import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
  4.  
    import org.springframework.web.bind.annotation.ControllerAdvice;
  5.  
    import org.springframework.web.bind.annotation.ExceptionHandler;
  6.  
    import org.springframework.web.bind.annotation.ResponseBody;
  7.  
    import org.springframework.web.multipart.MaxUploadSizeExceededException;
  8.  
    import org.springframework.web.multipart.MultipartFile;
  9.  
     
  10.  
    import javax.servlet.http.HttpServletRequest;
  11.  
    import javax.servlet.http.HttpServletResponse;
  12.  
    import javax.validation.constraints.Max;
  13.  
    import java.io.IOException;
  14.  
     
  15.  
    /**
  16.  
    * @author winnie
  17.  
    * @PackageName:org.springframework.myspringboot.exception
  18.  
    * @Description TODO
  19.  
    * @date 2022/8/3 18:25
  20.  
    */
  21.  
    @ControllerAdvice
  22.  
    public class MyCustomMaxUploadSizeException {
  23.  
    //这里注意如果是参数中有不存在的参数就会导致我们的全局异常失效
  24.  
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
  25.  
    @ResponseBody
  26.  
    public String MyException(HttpServletRequest request,
  27.  
    HttpServletResponse response,
  28.  
    MaxUploadSizeExceededException e
  29.  
    )throws IOException {
  30.  
     
  31.  
    // response.setContentType("text/html;charset=utf-8");
  32.  
    // response.getWriter().write("上传的文件的大小是超过了最大限制");
  33.  
    return "上传的文件的大小是超过了最大限制";
  34.  
    }
  35.  
    }
学新通

这里是一个比较简单的demo,我们也可以返回自定义的错误视图

例如,引入thymeleaf依赖

  1.  
    <dependency>
  2.  
    <groupId>org.springframework.boot</groupId>
  3.  
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4.  
    <version>2.2.5.snapshot</version>
  5.  
    </dependency>
  1.  
    package org.springframework.myspringboot.exception;
  2.  
     
  3.  
     
  4.  
    import org.springframework.boot.logging.java.SimpleFormatter;
  5.  
    import org.springframework.web.bind.annotation.ControllerAdvice;
  6.  
    import org.springframework.web.bind.annotation.ExceptionHandler;
  7.  
    import org.springframework.web.multipart.MaxUploadSizeExceededException;
  8.  
    import org.springframework.web.servlet.ModelAndView;
  9.  
    import org.springframework.web.servlet.View;
  10.  
     
  11.  
    import javax.servlet.http.HttpServletRequest;
  12.  
    import javax.servlet.http.HttpServletResponse;
  13.  
    import java.io.IOException;
  14.  
    import java.text.SimpleDateFormat;
  15.  
    import java.util.Date;
  16.  
     
  17.  
    /**
  18.  
    * @author winnie
  19.  
    * @PackageName:org.springframework.myspringboot.exception
  20.  
    * @Description TODO
  21.  
    * @date 2022/8/3 18:25
  22.  
    */
  23.  
    @ControllerAdvice
  24.  
    public class MyCustomMaxUploadSizeException {
  25.  
    //这里注意如果是参数中有不存在的参数就会导致我们的全局异常失效
  26.  
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
  27.  
    public ModelAndView MyException(HttpServletRequest request,
  28.  
    HttpServletResponse response,
  29.  
    MaxUploadSizeExceededException e
  30.  
    )throws IOException {
  31.  
     
  32.  
    // response.setContentType("text/html;charset=utf-8");
  33.  
    // response.getWriter().write("上传的文件的大小是超过了最大限制");
  34.  
    ModelAndView modelAndView = new ModelAndView();
  35.  
    modelAndView.addObject("error",e.getMessage());
  36.  
    modelAndView.addObject("date",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
  37.  
    modelAndView.setViewName("uploadException.html");
  38.  
    return modelAndView;
  39.  
    }
  40.  
    }
学新通
  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>上传文件大小超过限制</title>
  6.  
    </head>
  7.  
    <body>
  8.  
    上传文件超过大小<br><br>
  9.  
    发生异常的日期:<p th:text="${date}"></p>
  10.  
    异常信息:<p th:text="${error}"></p>
  11.  
    </body>
  12.  
    </html>

发生异常的时候

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgcccfg
系列文章
更多 icon
同类精品
更多 icon
继续加载