开启ftp服务:
1、打开控制面板=====》程序和功能=====》 启用或关闭Windows功能
2、找到Internet Information Services,开启以下服务
勾选之后,ftp服务开启成功。
配置IIS,搭建ftp
1、Win+S键搜索iis,回车打开=====》右击网站 =====》添加FTP站点
填写FTP站点名称和物理路径,下一步。
填写IP地址(可直接填写0.0.0.0),选中无SSL,下一步
全勾上,完成。
ftp服务搭建完成!
使用文件传输工具测试是否可以连接ftp:
填写ip地址和端口号,点击连接,弹出一个窗口的话点击确认
如果能看到右下角的目录,且目录正确则表示连接成功,ftp可用
注意:如果要使用另一台电脑进行连接,则需要将两台电脑连在同一个局域网下,并且关闭作为ftp服务器主机的防火墙。
如果无法连接,可以关闭防火墙和杀毒软件。
上面的全部关闭。
接着打开控制面板=====》Windows Defender防火墙=====》允许应用或功能通过防火墙
更改设置=====》找到FTP服务器,勾选=====》允许其他应用
浏览=====》找到对应目录
点击打开,添加,确定。
再试试能否连接ftp服务器。
ftpUtil工具类:
package com.kgc.ymw.util;import org.apache.commons.net.ftp.*;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;/*** @author: BruceYoung* @date: 2023/5/23*/
@SuppressWarnings({"all"})
public class FtpUtil {private String Control_Encoding = "UTF-8";private FTPClient client = null;private String host = "";private int port = 21;private String user = "";private String password = "";private String ftpPath = "/";@SuppressWarnings("unused")private FtpUtil() {}public FtpUtil(String host, int port, String user, String pwd) {this.host = host;this.port = port;this.user = user;this.password = pwd;}/*** 获取当前FTP所在目录位置** @return*/public String getHome() {return this.ftpPath;}/*** 连接FTP Server** @throws IOException*/public static final String ANONYMOUS_USER = "anonymous";public void connect() throws Exception {if (client == null) {client = new FTPClient();}// 已经连接if (client.isConnected()) {return;}// 编码client.setControlEncoding(Control_Encoding);try {// 连接FTP Serverclient.connect(this.host, this.port);// 登陆if (this.user == null || "".equals(this.user)) {// 使用匿名登陆client.login(ANONYMOUS_USER, ANONYMOUS_USER);} else {client.login(this.user, this.password);}// 设置文件格式client.setFileType(FTPClient.BINARY_FILE_TYPE);// 获取FTP Server 应答int reply = client.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {client.disconnect();throw new Exception("connection FTP fail!");}FTPClientConfig config = new FTPClientConfig(client.getSystemType().split(" ")[0]);config.setServerLanguageCode("zh");client.configure(config);// 使用被动模式设为默认client.enterLocalPassiveMode();// 二进制文件支持client.setFileType(FTP.BINARY_FILE_TYPE);// 设置模式client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);} catch (IOException e) {throw new Exception("connection FTP fail! " + e);}}/*** 断开FTP连接** @param ftpClient* @throws IOException*/public void close() {if (client != null && client.isConnected()) {try {client.logout();client.disconnect();} catch (IOException e) {e.printStackTrace();}}}/*** 获取文件列表** @return*/public List<FTPFile> list() {List<FTPFile> list = null;try {FTPFile ff[] = client.listFiles(ftpPath);if (ff != null && ff.length > 0) {list = new ArrayList<FTPFile>(ff.length);Collections.addAll(list, ff);} else {list = new ArrayList<FTPFile>(0);}} catch (IOException e) {e.printStackTrace();}return list;}/*** 切换目录** @param path* 需要切换的目录* @param forcedIncrease* 如果目录不存在,是否增加*/public void switchDirectory(String path, boolean forcedIncrease) {try {if (path != null && !"".equals(path)) {boolean ok = client.changeWorkingDirectory(path);if (ok) {this.ftpPath = path;} else if (forcedIncrease) {// ftpPath 不存在,手动创建目录StringTokenizer token = new StringTokenizer(path, "\\//");while (token.hasMoreTokens()) {String npath = token.nextToken();client.makeDirectory(npath);client.changeWorkingDirectory(npath);if (ok) {this.ftpPath = path;}}}}} catch (Exception e) {e.printStackTrace();}}/*** 创建目录** @param path*/public void createDirectory(String path) {try {if (path != null && !"".equals(path)) {boolean ok = client.changeWorkingDirectory(path);if (!ok) {// ftpPath 不存在,手动创建目录StringTokenizer token = new StringTokenizer(path, "\\//");while (token.hasMoreTokens()) {String npath = token.nextToken();client.makeDirectory(npath);client.changeWorkingDirectory(npath);}}}client.changeWorkingDirectory(this.ftpPath);} catch (Exception e) {e.printStackTrace();}}/*** 删除目录,如果目录中存在文件或者文件夹则删除失败** @param path* @return*/public boolean deleteDirectory(String path) {boolean flag = false;try {flag = client.removeDirectory(path);} catch (IOException e) {e.printStackTrace();}return flag;}/*** 删除文件** @param path* @return*/public boolean deleteFile(String path) {boolean flag = false;try {flag = client.deleteFile(path);} catch (IOException e) {e.printStackTrace();}return flag;}/*** 上传文件,上传文件只会传到当前所在目录** @param localFile* 本地文件* @return*/public boolean upload(File localFile) {return this.upload(localFile, "");}/*** 上传文件,会覆盖FTP上原有文件** @param localFile* 本地文件* @param reName* 重名* @return*/public boolean upload(File localFile, String reName) {boolean flag = false;String targetName = reName;// 设置上传后文件名if (reName == null || "".equals(reName)) {targetName = localFile.getName();}FileInputStream fis = null;try {// 开始上传文件fis = new FileInputStream(localFile);client.setControlEncoding(Control_Encoding);client.setFileType(FTPClient.BINARY_FILE_TYPE);boolean ok = client.storeFile(targetName, fis);if (ok) {flag = true;}} catch (IOException e) {e.printStackTrace();}return flag;}/*** 下载文件,如果存在会覆盖原文件** @param ftpFileName* 文件名称,FTP上的文件名称* @param savePath* 保存目录,本地保存目录* @return*/public boolean download(String ftpFileName, String savePath) {boolean flag = false;File dir = new File(savePath);if (!dir.exists()) {dir.mkdirs();}FileOutputStream fos = null;try {String saveFile = dir.getAbsolutePath() + File.separator + ftpFileName;fos = new FileOutputStream(new File(saveFile));boolean ok = client.retrieveFile(ftpFileName, fos);if (ok) {flag = true;}} catch (IOException e) {e.printStackTrace();}return flag;}public static void main(String args[]) {// 创建FTP对象FtpUtil ftp = new FtpUtil("127.0.0.1", 21, "myftp", "myftp@2020");try {// 连接FTPftp.connect();// 移动工作空间、切换目录System.out.println("当前位置:" + ftp.getHome());ftp.switchDirectory("/test", true);System.out.println("当前位置:" + ftp.getHome());// 查询目录下的所有文件夹以及文件List<FTPFile> list = ftp.list();System.out.println("|-- " + ftp.getHome());for (FTPFile f : list) {System.out.println(" |-- [" + (f.getType() == 0 ? "文件" : "文件夹") + "]" + f.getName());}// 上传文件boolean r1 = ftp.upload(new File("C:\\Users\\joymt\\Documents\\ftp\\测试文件1.txt"), "测试文件2.txt");System.out.println("上传文件:" + r1);// 下载文件boolean r2 = ftp.download("测试文件2.txt", "C:\\Users\\joymt\\Documents\\ftp");System.out.println("下载文件:" + r2);// 删除文件boolean r3 = ftp.deleteFile("/test/测试文件2.txt");System.out.println("删除文件:" + r3);// 删除目录boolean r4 = ftp.deleteDirectory("/test");System.out.println("删除目录:" + r4);} catch (Exception e) {e.printStackTrace();}ftp.close();}}
工具类最后有测试代码。
文件上传代码:
public Map<String, Object> insertSelective(Product product, MultipartFile file, HttpServletRequest request) throws Exception {HashMap<String, Object> map = new HashMap<>();String filename = file.getOriginalFilename();String extension = FilenameUtils.getExtension(filename);if (!(extension.equals("png") || extension.equals("pneg") || extension.equals("jpg") || extension.equals("jpeg"))) {map.put("msg", "文件格式不正确");return map;}if (file.getSize() == 0) {map.put("msg", "文件不能为空");return map;}if (file.getSize() > 5 * 1024 * 1024) {map.put("msg", "文件大小超过5M");return map;}String newFilename = UUID.randomUUID().toString() + "." + extension;// 创建FTP对象FtpUtil ftp = new FtpUtil("127.0.0.1", 21, null , null);// 连接FTPftp.connect();System.out.println("当前位置:" + ftp.getHome());String path = request.getSession().getServletContext().getRealPath("upload");File file1 = new File(path, newFilename);if (!file1.exists()){file1.mkdirs();}file.transferTo(new File(path, newFilename));// 上传文件boolean r1 = ftp.upload(file1, newFilename);System.out.println("上传文件:" + r1);//关闭连接ftp.close();if (StringUtils.isEmpty(product.getCategorylevel2id())) {product.setCategorylevel2id(0);}if (StringUtils.isEmpty(product.getCategorylevel3id())) {product.setCategorylevel3id(0);}product.setId(UUID.randomUUID().toString());product.setIsdelete(0);product.setFilename(newFilename);product.setCreatedate(new Date());if (productMapper.insertSelective(product) != 1) {throw new Exception("数据库添加失败!");}solrClient.addBean(product);solrClient.commit();return map;}