본문 바로가기
IT/Spring

Spring Boot - File Upload / Download

by 최고영회 2020. 1. 20.
728x90
반응형
SMALL

File Upload

Controller

@ApiOperation(value = "소명 완료") 
@ApiResponses({ @ApiResponse(code = 200, message = "success") }) 
@PostMapping(value = "/elucidate/complete") 
public ResponseEntity<Void> completeElucidate( 
  @ApiParam(value = "문서정보 Json", required = true) @RequestParam("doc") String docJson, 
  @ApiParam(value = "소명 내용 파일", required = false) @RequestParam("file") MultipartFile file, 
  HttpServletRequest req) { 
  
  docService.completeElucidate(new Gson().fromJson(docJson, DocDto.class), file); 
  
  return new ResponseEntity<Void>(HttpStatus.CREATED); 
}

Service

@Transactional 
public void completeElucidate(MultipartFile file) { 
  Doc doc = docRepo.findById(elucidateDoc.getNo()).orElseThrow(() -> new ResourceNotFoundException("Doc", "docNo", elucidateDoc.getNo())); 
  // ... 생략 
  if (file != null) { 
    String fileOrgName = file.getOriginalFilename(); 
    String fileExtention = FilenameUtils.getExtension(fileOrgName); 
    DocLayout layout = layoutService.findById(doc.getDocLayout()); 
    
    if (!CommonUtils.null2str(layout.getAllowFileFormat(), "").contains(fileExtention)) { 
      throw new FileUploadException("Can not upload `."+fileExtention+"` File."); 
    } 
        
    // 파일 정보 저장 
    String saveFileName = prop.getFileLocation() + UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExtention; 
    doc.setAttachFile(new AttachFile(fileOrgName, saveFileName)); 
    
    // 파일 저장 
    File saveFile = new File(saveFileName); 
    saveFile.getParentFile().mkdir(); 
    try { 
      file.transferTo(saveFile); 
    } catch (Exception e) { 
      throw new FileUploadException("Faild to upload attachment file"); 
    } 
  } 
}

File Download

Controller

@ApiOperation(value = "첨부 파일 다운로드") 
@ApiResponses({ @ApiResponse(code = 200, message = "success") }) 
@GetMapping(value = "/{docNo}/downloadfile") 
public ResponseEntity<Resource> downloadFile(
  @ApiParam(value = "문서 고유 번호", required = true) @PathVariable("docNo") long docNo, 
  HttpServletRequest req) throws FileNotFoundException { 

  AttachFile fileInfo = docService.getAttachFile(docNo, provider.getUserNo(req)); 
  File file = new File(fileInfo.getFilePath()); 
  InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); 
  
  return ResponseEntity.ok() 
    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileInfo.getFileOrgName() + "\"") 
    .contentLength(file.length()) 
    .contentType(MediaType.parseMediaType("application/octet-stream")) 
    .body(resource); 
}

Service

@Transactional 
public AttachFile getAttachFile(long docNo, long userNo) { 
  Doc doc = docRepo.findById(docNo).orElseThrow(() -> new ResourceNotFoundException("Doc", "docNo", docNo)); 
  if (!doc.getApproverList().stream().anyMatch(u -> u.getUser().getNo() == userNo)) { 
    throw new ForbiddenException("Can not read this document, You have not authority"); 
  } 
  
  AttachFile fileInfo = doc.getAttachFile(); 
  if (fileInfo == null || CommonUtils.isNull(fileInfo.getFilePath())) { 
    throw new ResourceNotFoundException("File", "docNo", docNo); 
  } 
  
  File file = new File(fileInfo.getFilePath()); 
  if (file.exists()) { 
    return fileInfo; 
  } 
  throw new ResourceNotFoundException("File", "docNo", docNo); 
}

Test by swagger

Test by postman

728x90
반응형
LIST