java后端http大文件传输接口笔记

笔记

接口方

package com.chinaums.demo.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RequestMapping("/test")
@RestController
public class TestController {

    /**
     * 大文件传输
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping("/downloadBigFile")
    public void downloadBigFile(HttpServletResponse response) throws IOException {
        File file = new File("C:\\Users\\daen\\Desktop\\2.iso");
        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        int len;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        outputStream.flush();
        fileInputStream.close();
    }

}

下载方

package com.chinaums.demo.example;

import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class testA {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String path = "C:\\Users\\daen\\Desktop\\555.iso";
        RequestCallback requestCallback = request -> request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
        //对响应进行流式处理而不是将其全部加载到内存中
        restTemplate.execute("http://172.16.111.228:10088/mp/test/downloadBigFile", HttpMethod.GET, requestCallback, clientHttpResponse -> {
            //需要判断一下文件是否已经存在
            Files.copy(clientHttpResponse.getBody(), Paths.get(path));
            return null;
        });
    }

}

posted @ 2022-10-27 11:24  DaenMax  阅读(697)  评论(0编辑  收藏  举报