1、添加依赖
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
2、上传
@ResponseBody
@PostMapping("/image")
@ApiOperation("上传图片当前服务器")
public Result upload1(@RequestParam(value="file") MultipartFile multipartFile) {
Result result = new Result();
try {
//获取原始图片名称
String oddName = multipartFile.getOriginalFilename();
//获取原始图片扩展名
String suffix = oddName.substring(oddName.lastIndexOf("."));
//重新命名图片
long time = new Date().getTime();
String prefix = UUID.randomUUID().toString().replace("-", ""); //设置为随机数
String newName = "file_" + prefix + "_" + time + suffix;
// 图片上传
String filepath = new DateTime().toString("yyyy/MM/dd/HH");
boolean flag = FtpUtil.uploadFile(host, Integer.parseInt(port), username, password, basePath, filepath , newName, multipartFile.getInputStream());
if (flag) {
result.setSuccess(true);
result.setResult(basePath +"/"+ filepath + "/" + newName);
return result;
}else {
result.setSuccess(false);
result.setMessage("上传失败.");
return result;
}
} catch (IOException e) {
e.printStackTrace();
result.setSuccess(false);
result.setMessage("上传失败.");
return result;
}
}
ftp上传工具类
public class FtpUtil {
/**
* Description: 向FTP服务器上传文件
*
* @param host FTP服务器hostname
* @param port FTP服务器端口 21
* @param username FTP登录账号
* @param password FTP登录密码
* @param basePath FTP服务器基础目录,需要绝对路径 比如:/home/ftpuser/www/images
* @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String host, int port, String username, String password, String basePath,
String filePath, String filename, InputStream input) throws IOException {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
//切换到上传目录
if (!ftp.changeWorkingDirectory(basePath + filePath)) {
//如果目录不存在创建目录
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) {
if (!ftp.makeDirectory(tempPath)) {
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
//设置上传文件的类型为二进制类型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
//上传文件
if (!ftp.storeFile(filename, input)) {
System.out.println("uploadFile return 2...");
return result;
}
input.close();
ftp.logout();
result = true;
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
}
下载回显 path 未路径+文件名
@ApiOperation("ftp图片回显")
@GetMapping("/downloadPic")
public void downloadPic(@RequestParam("path") String path, HttpServletResponse response) {
FTPClient ftp = new FTPClient();
String remotePath = path.substring(0, path.lastIndexOf("/"));
String fileName = path.substring(path.lastIndexOf("/") + 1);
try {
int reply;
ftp.connect(host, Integer.parseInt(port));
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
}
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
InputStream in = ftp.retrieveFileStream(fileName);
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("charset", "utf-8");
response.addHeader("Pragma", "no-cache");
String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
ServletOutputStream sos = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
sos.write(buffer, 0, len);
}
in.close();
sos.close();
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
}
3、下载图片
/**
* Description: 从FTP服务器下载文件【使用ftp客户端下载】
*
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @return
*/
@PostMapping("/downloadImage")
@ApiOperation(“ftp下载图片”)
public boolean downloadFile(@RequestParam(“url”) String remotePath,
@RequestParam(“fileName”) String fileName,
HttpServletRequest request) {
String contextPath = request.getContextPath();
String localPath = “D:/web/img/pic”;
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, Integer.valueOf(port));
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
// 设置被动模式,开通一个端口来传输数据
ftp.enterLocalPassiveMode();
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File file = new File(localPath);
if (!file.exists()) {
file.mkdirs();
}
File localFile = new File(localPath + “/” + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
上传到项目路径
InputStream inputStream = multipartFile.getInputStream();
String contextPath = this.getClass().getClassLoader().getResource("").getPath();
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
File fs = new File(courseFile+"/image/");
if(!fs.exists()){
fs.mkdirs();
}
File f = new File(courseFile+"/image/"+multipartFile.getOriginalFilename());
multipartFile.transferTo(f);