Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

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

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}
Answer from fateddy on Stack Overflow
๐ŸŒ
Oodlestechnologies
oodlestechnologies.com โ€บ blogs โ€บ how-to-download-a-file-directly-from-url-in-spring-boot
How To Download A File Directly From URL In Spring Boot
February 14, 2020 - You can download a file directly by using direct download link URL. http://localhost:8080/downloadTestFile ยท 2. Download File using InputStream to HttpServletResponse ยท To read files in java we can use Reader or Stream. But for text data Reader is the good option to use but for binary data, ...
Top answer
1 of 7
269

Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

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

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}
2 of 7
71

The below Sample code worked for me and might help someone.

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/app")
public class ImageResource {

    private static final String EXTENSION = ".jpg";
    private static final String SERVER_LOCATION = "/server/images";

    @RequestMapping(path = "/download", method = RequestMethod.GET)
    public ResponseEntity<Resource> download(@RequestParam("image") String image) throws IOException {
        File file = new File(SERVER_LOCATION + File.separator + image + EXTENSION);

        HttpHeaders header = new HttpHeaders();
        header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=img.jpg");
        header.add("Cache-Control", "no-cache, no-store, must-revalidate");
        header.add("Pragma", "no-cache");
        header.add("Expires", "0");

        Path path = Paths.get(file.getAbsolutePath());
        ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

        return ResponseEntity.ok()
                .headers(header)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }

}
Discussions

java - How to download file from url using Spring MVC? - Stack Overflow
But when i click on download i am getting file not found exception. Iam thinking that problem is due to the url value. More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 22, 2017
java - Downloading a file from spring controllers - Stack Overflow
I have a requirement where I need to download a PDF from the website. The PDF needs to be generated within the code, which I thought would be a combination of a freemarker and a PDF generation fram... More on stackoverflow.com
๐ŸŒ stackoverflow.com
spring mvc - How to download file from a URL and save/replace it in a folder using Java 8? - Stack Overflow
I need to download the files from the URLs and store it in separate folders to avoid conflicts. Such as, the first index.csv file will be downloaded to a folder AWSStorageGateway and the second one to folder AmazonS3. Or another approach could be to store those files in 1 folder by changing filenames like AWSStorageGateway.csv and AmazonS3.csv. If the files already exist, it needs to be replaced with the new one. The project uses Java 8 and Spring ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Spring: how to download file? - Stack Overflow
I want to save zip archive from server to user computer. I have web page that shows some information about this file and has a download button. In my controller action on button simply redirect on More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 69423234 โ€บ download-file-from-external-url-using-spring-boot
java - Download file from external url using spring boot - Stack Overflow
I want to download the file coming from an external url. But I'm getting errors. Is there any better way to achieve this? This is my code: public ResponseEntity downloadAsset() throws IOException {...
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - Another highly used library for IO operation is Apache Commons IO. We can see from the Javadoc that thereโ€™s a utility class named FileUtils that we use for general file manipulation tasks. To download a file from a URL, we can use this one-liner:
๐ŸŒ
Medium
medium.com โ€บ @pasanmanohara โ€บ download-a-pdf-file-from-a-url-in-the-spring-boot-java-30fa325d6ab9
Java | Spring boot | Download a PDF file from a URL in the | by Pasan Manohara | Medium
August 30, 2023 - The @Service annotation from the Spring framework indicates that this class is a Spring-managed service. load() method: This is the main method of the service responsible for loading a PDF file from a given URL and saving it to the local filesystem.
๐ŸŒ
Javainuse
javainuse.com โ€บ spring โ€บ boot-file-download
Spring Boot File Download - Hello World Example
In the above FileDownloadController set the Content-Disposition as attachment and again go to the url http://localhost:8080/download/file/soa.pdf So our application is now working good. Download it - Spring Boot File Download Example ยท 1Z0-830 Java SE 21 Developer Certification Prepare with Notes and Real Time Practice Tests DP-600 Microsoft Fabric Analytics Engineer Prepare with Notes and Real Time Practice Tests SC-401 Microsoft Information Security Administrator Prepare with Notes and Real Time Practice Tests 1Z0-819 Java SE 11 Developer Certification Prepare with Notes and Real Time Pract
๐ŸŒ
CodeJava
codejava.net โ€บ frameworks โ€บ spring-boot โ€บ file-download-upload-rest-api-examples
Spring Boot File Download and Upload REST API Examples
November 16, 2023 - You can click Save Response > Save to a file to store the file on disk:Those are some code examples about File upload API and File download API implemented in Java and Spring framework. You can get the sample project code from this GitHub repo.To see the coding in action, I recommend you watch my video below: Spring Boot File Upload Tutorial (Upload and Display Images)
Find elsewhere
๐ŸŒ
GitHub
gist.github.com โ€บ balvinder294 โ€บ 3ff3f890009f562ea03807988db35209
Fetch Image from URL and save locally in Spring Boot(Java) ยท GitHub
Download ZIP ยท Fetch Image from URL and save locally in Spring Boot(Java) Raw ยท fetch-file-from-url-spring-boot.java ยท This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
๐ŸŒ
o7planning
o7planning.org โ€บ 11765 โ€บ spring-boot-file-download
Spring Boot File Download Example | o7planning.org
package org.o7planning.sbdownload; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootDownloadApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDownloadApplication.class, args); } } Write a method to return ResponseEntity. This object wraps the InputStreamResource object (which is data of the file downloaded by user). ... package org.o7planning.sbdownload.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOExceptio
Top answer
1 of 2
1

Try this:

@RequestMapping(value="/viewAttach", method = RequestMethod.GET)
public ModelAndView viewAttach(@RequestParam(value="article_id", required = true) String article_ref, HttpSession session, HttpServletResponse response) 
{

    /* *** Check Session *** */
    try {

        // Direclty from pier.content.GetContent written by ang94402

        URL url = new URL(binaryURL);           
        response.setHeader("Content-disposition", "attachment;filename=" + binary.getName());

        //Set the mime type for the response
        response.setContentType("application/pdf");

        // URLConnection connection = url.openConnection();
        InputStream is = url.openStream();

        BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
        int len;
        byte[] buf = new byte[1024];
        while ( (len = is.read(buf)) > 0 ) {
            outs.write(buf, 0, len);
        }
        outs.close();

    } catch (MalformedURLException e) {
        logger.error("Error ModelAndView.viewMain - MalformedURLException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
        return null;
    } catch (IOException e) {
        logger.error("Error ModelAndView.viewMain - IOException : " + e.toString() + " -- " + e.getStackTrace()[0].toString());
        return null;
    }


    return null;

}
2 of 2
0

This is just a pseudo code. Change it as per your needs.

 InputStream is = getClass().getResourceAsStream("filename");

First try to figure out that getClass() points to which directory.(Not sure, but it should be HOME of your App ?). Then place your file into same location, if its not.

Hope this would help. source

๐ŸŒ
javathinking
javathinking.com โ€บ blog โ€บ how-can-i-download-and-save-a-file-from-the-internet-using-java
How to Download and Save a File from a URL Using Java: Step-by-Step Guide โ€” javathinking.com
FileUtils.copyURLToFile(url, destinationFile, 5000, 10000); // Timeouts: 5s connection, 10s read System.out.println("File downloaded successfully to: " + savePath); } catch (MalformedURLException e) { System.err.println("Invalid URL: " + ...
๐ŸŒ
DevGlan
devglan.com โ€บ spring-boot โ€บ spring-boot-file-upload-download
Uploading and Downloading Files with Spring Boot
In this case, the file is sent as using Form data and the same is retrieved in the Spring controller Rest as a Multipart file. It is a representation of an uploaded file received in a multipart request. In the below implementation, we are Copying all bytes from an input stream to a file. By default, the copy fails if the target file already exists or is a symbolic link. Hence, we are using standard copy option as REPLACE_EXISTING. Once, this process is completed, the response will be the download URL of the file.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-download-file-url
Java Download File from URL | DigitalOcean
August 4, 2022 - downloadUsingStream: In this method of java download file from URL, we are using URL openStream method to create the input stream. Then we are using a file output stream to read data from the input stream and write to the file. downloadUsingNIO: In this download file from URL method, we are ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 72136946 โ€บ how-to-download-file-from-a-url-and-save-replace-it-in-a-folder-using-java-8
spring mvc - How to download file from a URL and save/replace it in a folder using Java 8? - Stack Overflow
I think you can do that in pure java. With spring and nio, you can definitly do this task. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Community Asks Sprint Announcement โ€“ January 2026: Custom site-specific badges! Stack Overflow chat opening up to all users in January; Stack Exchange chat... ... To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Top answer
1 of 3
1

In your controller method you can add this code to get file download

File file = new File("fileName");
FileInputStream in = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
in.read(content);
ServletContext sc = request.getSession().getServletContext();
String mimetype = sc.getMimeType(file.getName());
response.reset();
response.setContentType(mimetype);
response.setContentLength(content.length);
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
org.springframework.util.FileCopyUtils.copy(content, response.getOutputStream());
2 of 3
0

You don't have to know how to get the path, because the path is defined by the user :) But if your looking for the download path, check the source code of the website and where the download button links to. Usually you can see it in the beginning of the <form>.

If you are just looking for download a file:

public void download(String filename, String url) {

    URL u;
    InputStream is = null;
    DataInputStream dis;
    String s;

    try{
      u = new URL(url);

      // throws an IOException
      is = u.openStream();

      dis = new DataInputStream(new BufferedInputStream(is));
      FileWriter fstream = new FileWriter(filename);
      BufferedWriter out = new BufferedWriter(fstream);

      while ((s = dis.readLine()) != null) {

          // Create file 
          out.write(s);
          //Close the output stream
          out.close();
      }

    }catch (Exception e){ //Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

    is.close();
}

Hope this helps...

๐ŸŒ
Springcloud
springcloud.io โ€บ post โ€บ 2023-03 โ€บ springboot-download
File Downloading in Spring Boot Applications - Spring Cloud
March 15, 2023 - This article provides guidance on how to download a single file, download a Gzip-compressed file, and download multiple files through a zip archive in a Spring Boot application.
๐ŸŒ
HowToDoInJava
howtodoinjava.com โ€บ home โ€บ spring mvc โ€บ spring mvc file download controller example
Spring MVC File Download Controller Example
May 28, 2024 - In this Spring Boot MVC download file controller example, learn to create the handler method and prevent hot linking of the download URLs. ... In a Spring MVC application, to download a resource, such as a static file, to the browser, we need to make certain changes in the controller method and in the application configuration. This Spring MVC application discusses those changes for enabling the file download functionality. These changes are applicable for a Spring Boot application as well. Configure resource handling to serve static files from the /WEB-INF/files/ directory (or any other directory where files are present).
๐ŸŒ
GitHub
github.com โ€บ pooyafils โ€บ upload-and-download-file-by-springboot
GitHub - pooyafils/upload-and-download-file-by-springboot: upload and download files such as image, pdf and more by springboot ยท GitHub
public MyFile saveImage(MultipartFile file, String description) { try { byte[] bytes = file.getBytes(); Path pathImage = Paths.get(path + file.getOriginalFilename()); Files.write(pathImage, bytes); } catch (IOException e) { e.printStackTrace(); } file.getOriginalFilename(); MyFile myFile = MyFile.builder() .name(file.getOriginalFilename()) .description(description) .path(path) .url(url + file.getOriginalFilename()) .build(); repository.save(myFile); return myFile; }
Forked by 2 users
Languages ย  Java