package be.mentoringsystems.merke.presentation; import be.mentoringsystems.merke.importer.VendorImporter; import java.util.UUID; import javax.servlet.ServletContext; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; 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.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; /** * * @author anthonyarents */ @RestController @RequestMapping("/import") public class ImportController { @Value("#{contextParameters.uploadPath}") private String uploadPath; @Autowired private ServletContext servletContext; @Autowired private VendorImporter vendorImporter; private static final Logger LOGGER = LogManager.getLogger(ImportController.class); @RequestMapping(value = "/vendors", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}, produces = {MediaType.TEXT_PLAIN_VALUE, MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public String importVendors( @RequestPart(name = "file") MultipartFile file, @RequestParam(name = "name") String name) throws Exception { if (file != null && !file.isEmpty()) { LOGGER.info("receiving file."); UUID fileId = UUID.randomUUID(); StringBuilder uploadPathBuilder = new StringBuilder(uploadPath); uploadPathBuilder.append("/").append(fileId.toString()); String mimeType = servletContext.getMimeType(file.getOriginalFilename()); String extension = FilenameUtils.getExtension(file.getOriginalFilename()); if (mimeType == null) { // Set to binary type if MIME mapping isnot found. mimeType = "application/octet-stream"; } java.io.File serverFile = new java.io.File(uploadPathBuilder.toString() + "." + extension); byte[] bytes = file.getBytes(); FileUtils.writeByteArrayToFile(serverFile, bytes); LOGGER.info("starting import."); vendorImporter.importFile(serverFile, fileId); //fileService.saveFile(fileDTO); LOGGER.info("File upload complete."); return "{\"success\": true }"; } else { throw new Exception("You failed to upload " + name + " because the file was empty."); } } }