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

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

下载

主要有下面的两种方式:

  • 通过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");
        //URLEncoder.encode为了解决中文乱码的问题
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date(file.lastModified()).toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new FileSystemResource(file));
    }

Controller

@RequestMapping("download")
public ResponseEntity<FileSystemResource> downloadFile() {
	return export(new File());//这里返回调用export的结果,自己构建一个File数据
}
点击查看完整代码


import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.util.Date;

/**
 * @author starsone
 * @date 2022/08/05 10:14
 */
@Controller
public class FileController {
    @RequestMapping("download")
    public ResponseEntity<FileSystemResource> downloadFile() {
        return export(new File("D:\\temp\\main.zip"));//这里返回调用export的结果
    }

    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=" + file.getName());//以时间命名文件,防止出现文件存在的情况,根据实际情况修改,我这里是返回一个xls文件
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date(file.lastModified()).toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new FileSystemResource(file));
    }

}

上传

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 "上传失败!";
}

多文件的话把参数改为MultipartFile[] fileList即可

3.Web页面上传文件

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

<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submFit" 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上传文件

//新建一个File,Android中许多API回调的接口都是以Uri形式,转为File即可
File file = new File(uri.getPath);
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();
OkhttpClient okHttpClient=new OkHttpClient();
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 实现上传 菜鸟教程

posted @ 2019-11-20 17:31  Stars-one  阅读(1070)  评论(0编辑  收藏  举报