cmglaze / test

0 stars 0 forks source link

How to convert a Spring to a file and download it in Spring Boot #137

Open cmglaze opened 1 year ago

cmglaze commented 1 year ago

EXAMPLE RESPONSE: To convert a Spring to a file and download it in Spring Boot, you can follow these steps:

  1. Create an instance of ResourceLoader to access the file.

@Autowired private ResourceLoader resourceLoader;

  1. Use the resourceLoader to load the file into an InputStream.

Resource resource = resourceLoader.getResource("classpath:path/to/file"); InputStream inputStream = resource.getInputStream();

  1. Create a byte array output stream and copy the contents of the input stream to the output stream.

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, len); }

  1. Set the content type and response headers.

response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=file.ext");

  1. Write the byte array output stream to the response output stream.

OutputStream outputStream = response.getOutputStream(); outputStream.write(byteArrayOutputStream.toByteArray()); outputStream.flush(); outputStream.close();