DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot

Trending

  • A Guide to Developing Large Language Models Part 1: Pretraining
  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  • Rethinking Recruitment: A Journey Through Hiring Practices
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot REST Service: Download Files

Spring Boot REST Service: Download Files

See how to download files from a Spring Boot REST service.

By 
Damodhara Palavali user avatar
Damodhara Palavali
·
Apr. 05, 19 · Code Snippet
Likes (10)
Comment
Save
Tweet
Share
56.2K Views

Join the DZone community and get the full member experience.

Join For Free

Image title

Download a File From a Spring Boot REST Service

On HBase, I was working on a REST API that could download an ingested file from a table with a JSON response. It needs to be downloaded as a JSON file from the UI. I created a REST service that downloads single and selected multiple files as ZIP files.

Below is my input, and I need to download it as a JSON file.

Image title

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HbaseRestController {
 @RequestMapping(value = “/files/ {
  file_name
 }”, method = RequestMethod.GET)
 public void getFile(
  @PathVariable(“file_name”) String fileName,
  HttpServletResponse response) {
  String testJson = ” {
   \\
   r\\ n\\\” name\\\”: \\\”Jungle Gym\\\”,
   \\r\\ n\\\” age\\\”: 25\\ r\\ n
  }”;
  try {
   // get your file as InputStream
   InputStream is = new ByteArrayInputStream(testJson.getBytes());
   // copy it to response’s OutputStream
   org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
   String filename = ”attachment;” + ”filename = ”+fileName;
   response.setContentType(“application / json”);
   response.setHeader(“Content - Disposition”, “attachment; filename = ”+filename + ”.json”);
   response.flushBuffer();
   System.out.println(“Filename————— -> ”+fileName);
  } catch (IOException ex) {
   System.out.println(“Error writing file to output stream.Filename was“ + fileName + ” == > ”+ex);
   throw new RuntimeException(“IOError writing file to output stream”);
  }

 }

 @RequestMapping(value = ”/downLoadZIPFile”, method = RequestMethod.GET)
  public void downLoadSearchFiles(HttpServletResponse response) {

   Map < String, String > jsonList = new HashMap < > ();
   jsonList.put(“F101”, “ {
    \\
    r\\ n\\\” name\\\”: \\\”TEst\\\”,
    \\r\\ n\\\” age\\\”: 25\\ r\\ n
   }”);
   jsonList.put(“F102”, “ {
    \\
    r\\ n\\\” name\\\”: \\\”Jungle Gym\\\”,
    \\r\\ n\\\” age\\\”: 26\\ r\\ n
   }”);
   jsonList.put(“F103”, “ {
    \\
    r\\ n\\\” name\\\”: \\\”Jungle Gym\\\”,
    \\r\\ n\\\” age\\\”: 27\\ r\\ n
   }”);

   try {
    response.setHeader(“Pragma”, “public”);
    response.setHeader(“Expires”, “0”);
    response.setHeader(“Cache - Control”, “must - revalidate, post - check = 0, pre - check = 0”);
    response.setHeader(“Content - type”, “application - download”);
    response.setHeader(“Content - Disposition”, “attachment; filename = -JSONSearchResultsData - ” +new SimpleDateFormat(“yyyyMMdd”).format(new Date()) + ”.zip”);
    response.setHeader(“Content - Transfer - Encoding”, “binary”);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(baos);
    for (Entry < String, String > entry: jsonList.entrySet()) {
     ZipEntry e = new ZipEntry(entry.getKey() + new SimpleDateFormat(“yyyyMMdd”).format(new Date()) + ”.” + ”json”);
     e.setSize(entry.getValue().length());
     e.setTime(System.currentTimeMillis());
     zipOutputStream.putNextEntry(e);

     InputStream is = new ByteArrayInputStream(entry.getValue().getBytes());
     IOUtils.copy(is, zipOutputStream);
     is.close();
     zipOutputStream.closeEntry();
    }
    zipOutputStream.close();

    byte[] zipBytes = baos.toByteArray();
    OutputStream outStream = response.getOutputStream();
    outStream.write(zipBytes);
    outStream.close();
    response.flushBuffer();
   } catch (Exception e) {}
  }
 }

Image title

Image title

Please share your comments and reviews!

REST Web Protocols Spring Framework Spring Boot Download

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!