com.sippnex.fileblade.controllers.UploadController Maven / Gradle / Ivy
package com.sippnex.fileblade.controllers;
import com.sippnex.fileblade.dtos.UploadResponseDto;
import com.sippnex.fileblade.entities.File;
import com.sippnex.fileblade.entities.UploadRequest;
import com.sippnex.fileblade.entities.UploadResponse;
import com.sippnex.fileblade.services.FilebladeItemService;
import com.sippnex.fileblade.services.UploadRequestService;
import com.sippnex.fileblade.util.IOProcessor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
@RestController
@RequestMapping("fileblade/upload")
public class UploadController {
final UploadRequestService uploadRequestService;
final FilebladeItemService filebladeItemService;
public UploadController(UploadRequestService uploadRequestService, FilebladeItemService filebladeItemService) {
this.uploadRequestService = uploadRequestService;
this.filebladeItemService = filebladeItemService;
}
@PostMapping("{uploadId}")
public UploadResponseDto upload(@PathVariable Long uploadId, @RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
UploadResponse uploadResponse;
Optional optionalUploadRequest = uploadRequestService.findById(uploadId);
if(optionalUploadRequest.isPresent()) {
UploadRequest uploadRequest = optionalUploadRequest.get();
try {
File file;
if(uploadRequest.getParentDirectory() == null) { // Root File (without parent directory)
file = new File(uploadRequest.getFileName(), IOProcessor.toByteArray(multipartFile.getInputStream()), multipartFile.getContentType());
} else { // Subfolder File (with parent directory)
file = new File(uploadRequest.getFileName(), IOProcessor.toByteArray(multipartFile.getInputStream()), multipartFile.getContentType(), uploadRequest.getParentDirectory());
}
filebladeItemService.save(file);
uploadRequestService.delete(uploadRequest);
uploadResponse = new UploadResponse(uploadId, true, file.getId(), file.getPath());
} catch(Exception e) {
uploadResponse = new UploadResponse(uploadId, false);
}
} else {
uploadResponse = new UploadResponse(uploadId, false);
}
return UploadResponseDto.parse(uploadResponse, "http://" + request.getServerName() + ":" + request.getServerPort());
}
}