argos/dmp-backend/web/src/main/java/eu/eudat/controllers/FileController.java

53 lines
2.3 KiB
Java

package eu.eudat.controllers;
import eu.eudat.logic.managers.FileManager;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.files.ContentFile;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
/**
* Created by ikalyvas on 3/15/2018.
*/
@RestController
@CrossOrigin
@RequestMapping(value = {"/api/files"})
public class FileController extends BaseController {
private FileManager fileManager;
@Autowired
public FileController(ApiContext apiContext, FileManager fileManager) {
super(apiContext);
this.fileManager = fileManager;
}
@RequestMapping(method = RequestMethod.POST, value = {"/upload"})
public ResponseEntity<ResponseItem<List<ContentFile>>> handleFileUpload(@RequestParam("file") MultipartFile[] files) throws IOException {
return ResponseEntity.status(HttpStatus.OK).body(
new ResponseItem<List<ContentFile>>().status(ApiMessageCode.NO_MESSAGE).payload(fileManager.saveTempFile(files)));
}
@RequestMapping(method = RequestMethod.GET, value = {"/{id}"})
public ResponseEntity<Resource> handleFileUpload(@PathVariable(name = "id") String id,
@RequestParam(name = "type") String type,
@RequestParam(name = "location", required = false, defaultValue = "final") String location) throws IOException {
Resource resource = fileManager.getFile(id, type, location);
if (!resource.exists())
resource = new UrlResource(FileController.class.getClassLoader().getResource("images/default.png"));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "." + type + "\"")
.body(resource);
}
}