ExportImportController.java
package cz.vsb.crm.controller;
import cz.vsb.crm.dto.ImportReport;
import cz.vsb.crm.service.export.CsvExportService;
import cz.vsb.crm.service.export.CsvImportService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
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 org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import java.io.IOException;
@RestController
@RequestMapping("/api")
public class ExportImportController {
private static final MediaType TEXT_CSV = MediaType.parseMediaType("text/csv");
private final CsvExportService exportService;
private final CsvImportService importService;
public ExportImportController(CsvExportService exportService, CsvImportService importService) {
this.exportService = exportService;
this.importService = importService;
}
@GetMapping("/export/products.csv")
public ResponseEntity<StreamingResponseBody> exportProducts() {
return csv("products.csv", exportService::writeProducts);
}
@GetMapping("/export/orders.csv")
public ResponseEntity<StreamingResponseBody> exportOrders() {
return csv("orders.csv", exportService::writeOrders);
}
@PostMapping(value = "/import/products", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ImportReport importProducts(@RequestParam("file") MultipartFile file) throws IOException {
return importService.importProducts(file.getInputStream());
}
private ResponseEntity<StreamingResponseBody> csv(String filename, StreamingResponseBody body) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
.contentType(TEXT_CSV)
.body(body);
}
}