package com.SpringBootFileHandling.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
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 org.springframework.web.multipart.MultipartFile;
@RestController
public class FileController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFile(@RequestParam("file") MultipartFile file){
String filePath = System.getProperty("user.dir") + "/Uploads" + File.separator + file.getOriginalFilename();
String fileUploadStatus;
try {
FileOutputStream fout = new FileOutputStream(filePath);
fout.write(file.getBytes());
fout.close();
fileUploadStatus = "File Uploaded Successfully";
}
catch (Exception e) {
e.printStackTrace();
fileUploadStatus = "Error in uploading file: " + e;
}
return fileUploadStatus;
}
@RequestMapping(value = "/getFiles", method = RequestMethod.GET)
public String[] getFiles()
{
String folderPath = System.getProperty("user.dir") +"/Uploads";
File directory= new File(folderPath);
String[] filenames = directory.list();
return filenames;
}
@RequestMapping(value = "/download/{path:.+}", method = RequestMethod.GET)
public ResponseEntity downloadFile(@PathVariable("path") String filename) throws FileNotFoundException {
String fileUploadpath = System.getProperty("user.dir") +"/Uploads";
String[] filenames = this.getFiles();
boolean contains = Arrays.asList(filenames).contains(filename);
if(!contains) {
return new ResponseEntity("FIle Not Found",HttpStatus.NOT_FOUND);
}
String filePath = fileUploadpath+File.separator+filename;
File file= new File(filePath);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
String contentType = "application/octet-stream";
String headerValue = "attachment; filename=\"" + resource.getFilename() + "\"";
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, headerValue)
.body(resource);
}
}