728x90
일단 참공
FilleZilla 서버 설치
사용법 확인!
라이브러리 추강(ftp client)
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
FtpUtils
package com.minu.merong.utils;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.SocketException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component //Bean 생성
public class FtpUtils {
//Ftp 서버에 들어가기 위해 필요한것
@Value("localhost")
private String server;
@Value("21")
private int port;
@Value("e7e")
private String username;
@Value("suzi")
private String password;
private FTPClient ftp;
//FTPClient 객체를 통한 ftp 서버 연결
public void open() throws SocketException, IOException {
log.debug("server:" + server);
log.debug("port:" + port);
log.debug("username:" + username);
log.debug("password:" + password);
ftp = new FTPClient();
ftp.setControlEncoding("UTF-8");
//로그로 서버와 주고받은 명령어 결과들을 출력 받을 수 있음
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
ftp.connect(server, port);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
log.error("FTPClient:: server connection failed.");
}
ftp.setSoTimeout(1000);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
}
public void close() throws IOException {
ftp.logout();
ftp.disconnect();
}
//ftp 서버에 전송받은 파일 UPLOAD
public void upload(MultipartFile file) throws IOException {
open();
InputStream inputStream = null;
inputStream = file.getInputStream();
//아래 라인이 핵심, put과 같음
ftp.storeFile(file.getOriginalFilename(), inputStream);
inputStream.close();
close();
}
// ftp download
public void downlod(String fName, HttpServletResponse resp) throws IOException {
String fileName = URLEncoder.encode(fName, "UTF-8");
//String fileName2 = "미우.jpg";
// 브라우져 별 기본 세팅이 쪼메 다름(구글 참공, 여기선 크롬기준으로)
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment; filename=\""+ fileName + "\"");
open(); //ftp 연결
OutputStream outputStream = new BufferedOutputStream(resp.getOutputStream());
InputStream inputStream = null;
//get에 해당(뽀인또)
inputStream =ftp.retrieveFileStream("/"+fName);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream.write(bytesArray, 0, bytesRead);
}
boolean success = ftp.completePendingCommand();
log.debug("check: " + success);
outputStream.close();
inputStream.close();
//ftp 닫는거
close();
}
}
FtpController
package com.minu.merong.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.minu.merong.utils.FtpUtils;
@Controller
@RequestMapping("/ftp")
public class FtpController {
@Autowired
private FtpUtils ftpUtils;
@GetMapping("/main")
public String main() {
return "ftpmain";
}
// ftp download
// 다운로드는 꼬옥 ftp 클라이언트를 쓰지 않아도 됨!
// upload만 ftp를 쓰공, 다운로드는 해당 폴더를 외부파일 맵핑 했을 경우
// 이전에 배웠던 a 태그에 download속성을 부여하는 방식으로도
// 충분히 사용할 수 있을 것이당!
@GetMapping("/download/{fname}")
public void down(@PathVariable String fname, HttpServletResponse resp) throws IOException {
ftpUtils.downlod(fname, resp);
}
@PostMapping("/upTest")
@ResponseBody // 그냥jsp안 만들라공!!
public String upTest(MultipartFile myFile) throws IOException {
ftpUtils.upload(myFile);
return "OK";
}
}
ftpmain
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ftpClient 테스통</title>
</head>
<body>
<form action="/merong/ftp/upTest" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" value="">
<button>떠언쏭</button>
</form>
</body>
</html>
package com.minu.merong.utils;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.SocketException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component //Bean 생성
@PropertySource("classpath:config/props/ftpConf.properties")
public class FtpUtils {
//Ftp 서버에 들어가기 위해 필요한것
@Value("${myftp.server}")
private String server;
@Value("${myftp.port}")
private int port;
@Value("${myftp.username}")
private String username;
@Value("${myftp.password}")
private String password;
private FTPClient ftp;
//FTPClient 객체를 통한 ftp 서버 연결
public void open() throws SocketException, IOException {
log.debug("server:" + server);
log.debug("port:" + port);
log.debug("username:" + username);
log.debug("password:" + password);
ftp = new FTPClient();
ftp.setControlEncoding("UTF-8");
//로그로 서버와 주고받은 명령어 결과들을 출력 받을 수 있음
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
ftp.connect(server, port);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
log.error("FTPClient:: server connection failed.");
}
ftp.setSoTimeout(1000);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
}
public void close() throws IOException {
ftp.logout();
ftp.disconnect();
}
//ftp 서버에 전송받은 파일 UPLOAD
public void upload(MultipartFile file) throws IOException {
open();
InputStream inputStream = null;
inputStream = file.getInputStream();
//아래 라인이 핵심, put과 같음
ftp.storeFile(file.getOriginalFilename(), inputStream);
inputStream.close();
close();
}
// ftp download
public void downlod(String fName, HttpServletResponse resp) throws IOException {
String fileName = URLEncoder.encode(fName, "UTF-8");
//String fileName2 = "미우.jpg";
// 브라우져 별 기본 세팅이 쪼메 다름(구글 참공, 여기선 크롬기준으로)
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment; filename=\""+ fileName + "\"");
open(); //ftp 연결
OutputStream outputStream = new BufferedOutputStream(resp.getOutputStream());
InputStream inputStream = null;
//get에 해당(뽀인또)
inputStream =ftp.retrieveFileStream("/"+fName);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream.write(bytesArray, 0, bytesRead);
}
boolean success = ftp.completePendingCommand();
log.debug("check: " + success);
outputStream.close();
inputStream.close();
//ftp 닫는거
close();
}
}
'Spring > Spring 기초' 카테고리의 다른 글
e7e샘의 Tree(트리) (1) | 2023.09.04 |
---|---|
e7e샘의 스케줄러 설정 (0) | 2023.09.01 |
filezila사용해서 file전송 서버 만들기(ftp) (0) | 2023.09.01 |
e7e샘의 시큐리티 설정4(메뉴얼 로그인) (0) | 2023.08.31 |
e7e샘의 시큐리티 설정3 (0) | 2023.08.30 |