com.sippnex.fileblade.controllers.DownloadController Maven / Gradle / Ivy
package com.sippnex.fileblade.controllers;
import com.sippnex.fileblade.entities.File;
import com.sippnex.fileblade.services.FilebladeItemService;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
@RestController
@RequestMapping("fileblade/download")
public class DownloadController {
final FilebladeItemService filebladeItemService;
public DownloadController(FilebladeItemService filebladeItemService) {
this.filebladeItemService = filebladeItemService;
}
@GetMapping("{path:.*}")
public void download(@PathVariable String path, HttpServletResponse response) {
try {
Optional optionalFile = filebladeItemService.findFileByPath(path);
if(!optionalFile.isPresent()) {
System.out.print("Error downloading file: File " + path + " not found");
return;
}
File file = optionalFile.get();
InputStream inputStream = new ByteArrayInputStream(file.getContent());
IOUtils.copy(inputStream, response.getOutputStream());
response.setContentType(file.getContentType());
response.flushBuffer();
} catch (IOException ex) {
throw new RuntimeException("IOError writing file to output stream");
}
}
}