Java - Download(Stream) file from another server and write directly to response

 





  Here is an example code to download (Stream) file from another server and write directly to response



package com.example.testproject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;

@Controller
public class TestController {

    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response)
    {
        String url = "https://filesamples.com/samples/document/pdf/sample3.pdf";
        try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());) {
            byte dataBuffer[] = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                response.getOutputStream().write(dataBuffer, 0, bytesRead);
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }
}