spring Boot 如何像PHP的readfile函数一样真实的返回字节流?

dba5bblo  于 2022-12-18  发布在  Spring
关注(0)|答案(2)|浏览(229)

我在解决一个需求,我用的是springboot框架,现在有一个接口传入参数url,这个url是一个网络文件地址,接口收到请求后,用自己的网络请求网络文件,真实的返回给客户端,php的readfile函数可以解决这个问题,但是java语言中有这样的解决方案吗?我需要的是真实的返回客户端,而不是全部阅读后返回客户端

@Controller
@Api(tags = "test")
@RequestMapping("/test")
@CrossOrigin
public class TestController {

    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ApiOperation(value = "get")
    public ResponseEntity<FileSystemResource> test() throws IOException {
      
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"123\": 1}");
        Request request = new Request.Builder()
                .url("https://github.com/xujimu/ios_super_sign/archive/refs/heads/master.zip")
                .method("GET", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        
    }

}
flseospp

flseospp1#

您可以使用ResponseEntity<StreamingResponseBody>来实现此目的。
您已经选择了要返回的内容类型。我们最终返回了produces = MediaType.APPLICATION_NDJSON_VALUE
我们不得不修改处理rest请求的方式,从RestClient to WebClient ':

Flux<DataBuffer> dataStream = return webClient.method(method)
                .uri(url)
                .retrieve()
                .bodyToFlux(DataBuffer.class);

DataBufferUtils.write(dataStream, response.getOutputStream())
                .map(DataBufferUtils::release)
                .blockLast();

当我们终于让这个工作的时候,它真的很好用:)
您可以在https://www.baeldung.com/spring-mvc-sse-streams上看到其他一些示例。

5q4ezhmt

5q4ezhmt2#

我用java的URL类解决了这个问题

package com.api.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.api.common.result.PageReq;
import com.api.common.result.PageResult;
import com.api.common.result.Result;
import com.api.common.user.AddBalanceReq;
import com.api.constant.ResultCode;
import com.api.dao.ApiUserDao;
import com.api.dao.UserFlowDao;
import com.api.entity.ApiUserEntity;
import com.api.entity.UserFlowEntity;
import com.api.execption.ResRunException;
import com.api.service.ApiUserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import reactor.core.publisher.Flux;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.DataBuffer;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

@Controller
@Api(tags = "test")
@RequestMapping("/test")
@CrossOrigin
public class TestController {
 
    /**
     * 添加用户月
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ApiOperation(value = "get")
    public void test(String url, HttpServletResponse response) throws IOException {

        URL url1 = new URL(url);

        InputStream is = url1.openStream();

        int ch;
        while ((ch = is.read()) != -1) {
            response.getWriter().write(ch);
        }
        
    }

}

相关问题