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
🌐
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
🌐
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.
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

🌐
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 ...
🌐
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.
🌐
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.
🌐
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