Commit 75ecc423 authored by mcb's avatar mcb

commit

parent d15605be
package com.jz.common.utils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
/**
* @ClassName:
* @Author: Bellamy
* @Date: 2021/3/12
* @Version:
*/
public class FtpUtil {
/**
* Description: 向FTP服务器上传文件
* @param host FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param basePath FTP服务器基础目录
* @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) {
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);
//上传文件
if (!ftp.storeFile(filename, input)) {
return result;
}
input.close();
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
/**
* Description: 从FTP服务器下载文件
* @param host FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
String fileName, String localPath) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
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;
}
}
package com.jz.dmp.modules.controller;
import com.jz.common.constant.JsonResult;
import com.jz.common.constant.ResultCode;
import com.jz.common.utils.CommonUtils;
import com.jz.common.utils.FtpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
/**
* @ClassName:
* @Author: Bellamy
* @Date: 2021/1/12
* @Version:
*/
@RestController
@Api(tags = "图片处理")
public class PictureController {
@Value("${ftp.url}")
private String ftpUrl;
@Value("${ftp.port}")
private Integer port;
@Value("${ftp.username}")
private String username;
@Value("${ftp.password}")
private String password;
@PostMapping("/uploadPicture")
@ApiOperation(value = "图片上传")
@ResponseBody
public JsonResult uploadPicture(MultipartFile file, @RequestParam(name = "params",required = false) String params) {
JsonResult result = new JsonResult();
if (file.getSize() > 10240000) {
return JsonResult.error("图片格式太大,不能超过10MB!");
}
// 获取图片名称
String originalFilename = file.getOriginalFilename();
// 获取图片扩展名
String extensionName = originalFilename.substring(originalFilename.lastIndexOf("."));
// 重新命名图片
String picture = CommonUtils.generatePrimaryKeyId() + extensionName;
// 上传图片
try {
String filePath = "";
//if (params.equals("datasource")) {
filePath = "/dmp/datasource";
// }
boolean flag = FtpUtil.uploadFile(ftpUrl, port, username, password, "/", filePath, picture, file.getInputStream());
if (flag) {
String url = "/dmp/downloadPicture?url=" + filePath + "/" + picture;
result.setData(url);
result.setMessage("图片上传成功!");
} else {
result.setMessage("图片上传失败!");
result.setCode(ResultCode.INTERNAL_SERVER_ERROR);
}
} catch (IOException e) {
e.printStackTrace();
result.setMessage("图片上传失败!");
result.setCode(ResultCode.INTERNAL_SERVER_ERROR);
}
return result;
}
@GetMapping("/dmp/downloadPicture")
@ApiOperation(value = "图片下载")
public JsonResult downloadPicture(@RequestParam(name = "url") String url, HttpServletResponse response) {
JsonResult result = new JsonResult();
FTPClient ftp = new FTPClient();
String catalog = url.substring(url.lastIndexOf("=")+ 1);
String remotePath = catalog.substring(0, catalog.lastIndexOf("/") + 1);
String furl = url.substring(url.lastIndexOf("/") +1);
String suffix = catalog.substring(catalog.lastIndexOf("."));
try {
int reply;
ftp.connect(ftpUrl, port);
// 登录
ftp.login(username, password);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
}
ftp.enterLocalPassiveMode();
// 到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
InputStream in = ftp.retrieveFileStream(furl);
ServletOutputStream outputStream = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
// byte[] bytes = sos.toByteArray();
response.setHeader("Content-Disposition", "attachment;filename="+suffix);
IOUtils.copy(in, outputStream);
in.close();
outputStream.close();
ftp.logout();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (Exception ioe) {
}
}
}
return result;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment