ng-tracker/src/main/java/ru/ulstu/file/FileController.java
2018-11-23 16:45:40 +04:00

58 lines
2.4 KiB
Java

package ru.ulstu.file;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import ru.ulstu.configuration.Constants;
import ru.ulstu.core.model.response.Response;
import ru.ulstu.file.model.FileData;
import ru.ulstu.file.service.FileService;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import static java.nio.charset.StandardCharsets.UTF_8;
import static ru.ulstu.file.FileController.URL;
@RestController
@RequestMapping(URL)
public class FileController {
public static final String URL = Constants.API_1_0 + "files";
private final FileService fileService;
public FileController(FileService fileService) {
this.fileService = fileService;
}
@GetMapping("/download-tmp/{tmp-file-name}")
public ResponseEntity<byte[]> getFile(@PathVariable("tmp-file-name") String tmpFileName) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename='"
+ URLEncoder.encode(fileService.getTmpFileName(tmpFileName), UTF_8.toString()) + "'");
return new ResponseEntity<>(fileService.getTmpFile(tmpFileName), headers, HttpStatus.OK);
}
@GetMapping("/download/{file-id}")
public ResponseEntity<byte[]> getFile(@PathVariable("file-id") Integer fileId) throws UnsupportedEncodingException {
HttpHeaders headers = new HttpHeaders();
FileData fileData = fileService.getFile(fileId);
headers.add("Content-Disposition", "attachment; filename='" +
URLEncoder.encode(fileData.getName(), UTF_8.toString()) + "'");
return new ResponseEntity<>(fileData.getData(), headers, HttpStatus.OK);
}
@PostMapping("/uploadTmpFile")
public Response<String> upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
return new Response(fileService.uploadToTmpDir(multipartFile));
}
}