Spring框架学习笔记(7)——Spring Boot 实现上传和下载

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring框架学习笔记(7)——Spring Boot 实现上传和下载

Stars-one   2019-11-20 我要评论

最近忙着都没时间写博客了,做了个项目,实现了下载功能,没用到上传,写这篇文章也是顺便参考学习了如何实现上传,上传和下载做一篇笔记吧

下载

主要有下面的两种方式:

  • 通过ResponseEntity实现
  • 通过写HttpServletResponse的OutputStream实现

我只测试了ResponseEntity<InputStreamResource>这种方法可行,另外一种方法请各位搜索资料。

我们在controller层中,让某个方法返回ResponseEntity,之后,用户打开这个url,就会直接开始下载文件

这里,封装了一个方法export,负责把File对象转为ResponseEntity

public ResponseEntity<FileSystemResource> export(File file) {
    if (file == null) {
        return null;
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");//以时间命名文件,防止出现文件存在的情况,根据实际情况修改,我这里是返回一个xls文件
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    headers.add("Last-Modified", new Date().toString());
    headers.add("ETag", String.valueOf(System.currentTimeMillis()));

    return ResponseEntity
            .ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new FileSystemResource(file));
}

Controller

@RequestMapping("download")
public ResponseEntity<FileSystemResource> downloadFile() {
    return excelFileService.getGroupExcel(matchId);
}

上传

1.配置

spring boot使用上传功能,得先进行配置,spring boot配置方式有两种,一种是资源文件properties配置,另外一种方式则是yml配置

properties配置:

## MULTIPART (MultipartProperties)
# 开启 multipart 上传功能
spring.servlet.multipart.enabled=true
# 文件写入磁盘的阈值
spring.servlet.multipart.file-size-threshold=2KB
# 最大文件大小
spring.servlet.multipart.max-file-size=200MB
# 最大请求大小
spring.servlet.multipart.max-request-size=215MB

yml配置:

spring:
    servlet:
        multipart:
          enabled: true # 开启 multipart 上传功能
          max-file-size: 200MB # 最大文件大小
          max-request-size: 215MB # 最大文件请求大小
          file-size-threshold: 2KB # 文件写入磁盘的阈值

2.编写url请求

controller

@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
        return "上传失败,请选择文件";
    }

    String fileName = file.getOriginalFilename();
    String filePath = "/Users/itinypocket/workspace/temp/";//文件上传到服务器的路径,根据实际情况修改
    File dest = new File(filePath + fileName);
    try {
        file.transferTo(dest);
        LOGGER.info("上传成功");
        return "上传成功";
    } catch (IOException e) {
        LOGGER.error(e.toString(), e);
    }
    return "上传失败!";
}

3.Web页面上传文件

注意,input标签的name与url的请求参数名相同,上传只能使用post请求
单个文件上传:

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

多个文件上传:

input标签加上multiple属性,即可一次选择多个文件

<form method="post"  action="/upload" enctype="multipart/form-data">
    <input type="file" multiple name="file"><br>
    <input type="submit" value="提交">
</form>

4.Android端上传文件

使用okhttp上传文件

RequestBody filebody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
RequestBody body = new MultipartBody.Builder()
        .addFormDataPart("file", file.getName(), filebody)
        .build();
Request request = new Request.Builder()
        .url("http://192.168.1.106:8080/webapp/fileUploadPage")
        .post(body)
        .build();

Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.e(TAG, "请求失败:" + e.getMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.e(TAG, "请求成功!");
    }
});

参考链接:
spring boot文件下载
Spring Boot 文件上传与下载
Spring Boot教程(十三):Spring Boot文件上传
jsp 实现上传 菜鸟教程

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们