zoukankan      html  css  js  c++  java
  • 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");
        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 export(new FIle());//这里返回调用export的结果
    }
    

    上传

    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="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 实现上传 菜鸟教程

  • 相关阅读:
    树莓派ZeroW的Python中使用SQLite数据库
    树莓派Python读写配置文件--configparser库
    信号量示例——“生产者——消费者”实验
    互斥锁示例——模拟银行卡取钱
    管道通信(上)
    命名管道——进程通信案例
    文件I/O
    链表习题
    蓝桥杯ACM训练Day4——算法2-8~2-11:链表的基本操作
    C++——类模板几种常见的情况
  • 原文地址:https://www.cnblogs.com/stars-one/p/11899194.html
Copyright © 2011-2022 走看看