JAVA SMB 프로토콜 통한 파일 업로드 & 다운로드

JAVA SMB 프로토콜 통한 파일 업로드 & 다운로드

728x90

SMBJ

pom.xml

com.hierynomus smbj 0.10.0

Java

@Value("${file.upload.server}") private String server; @Value("${file.upload.sharedFolder}") private String sharedFolder; @Value("${file.upload.user}") private String user; @Value("${file.upload.password}") private String pass;

업로드

public void smbFileUpload(){ .... SMBClient client = new SMBClient(); try (Connection connection = client.connect(address)) { AuthenticationContext ac = new AuthenticationContext(user, pass.toCharArray(), null); Session session = connection.authenticate(ac); // Connect to Share try (DiskShare share = (DiskShare) session.connectShare(sharedFolder)) { File fileSource = new File(file.getOriginalFilename()); file.transferTo(fileSource); if(!share.folderExists(dateFolder)){ share.mkdir(dateFolder); } SmbFiles.copy(fileSource, share, "원하는 경로", true); } } catch(Exception e) { e.printStackTrace(); } }

다운로드

@GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public ResponseEntity fileDownload(@RequestHeader("User-Agent") String userAgent, @RequestParam String filename, @RequestParam String path, @RequestParam String originName) { byte[] outData = new byte[0]; String fileExg = FilenameUtils.getExtension(filename); try { SMBClient client = new SMBClient(); try (Connection connection = client.connect(server)) { AuthenticationContext ac = new AuthenticationContext(user, pass.toCharArray(), null); Session session = connection.authenticate(ac); // Connect to Share try (DiskShare share = (DiskShare) session.connectShare(sharedFolder)) { com.hierynomus.smbj.share.File file = share.openFile(path + File.separator + filename, EnumSet.of(AccessMask.GENERIC_READ), null, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OPEN, null); try ( InputStream fin = new BufferedInputStream(file.getInputStream()); ) { outData = IOUtils.toByteArray(fin); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } String downloadName = "다운로드 이름" 브라우저별 이름 처리 .... MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); String type = mimeTypesMap.getContentType(downloadName); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + downloadName) .header(HttpHeaders.CONTENT_TYPE, type) .contentLength(outData.length) .body(outData); }

참고

SMBJ 프로토콜 라이브러리를 0.10.0을 썼는데 그 보다 상위 버전을 사용하면 추가로 뭔가를 설정해줘야 하는데 찾다가 그냥 0.10.0 버전을 썼다..

그리고 SMB로 접속할 윈도우 서버에서 445 포트가 열려있어야 한다..

from http://amagrammer91.tistory.com/121 by ccl(A) rewrite - 2021-11-12 10:01:23