windows上搭建ftp服务器并上传文件,通过nginx服务反向代理方式根据ip在网页上打开上传到FTP文件

window搭建ftp服务器

ftp支持SSL创建证书链接

nginx服务,反向代理

window关闭ftp服务

nginx停止服务

<!--ftp服务 start-->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
        <!--ftp服务 end-->

        <!--lombok start-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
        <!--ftp服务 end-->

        <!--日志 start-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>
        <!--日志end-->

        <!-- -->
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
package com.wonders.ftp.constroller;

import com.wonders.ftp.entity.Ftp;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import java.io.*;

public class FtpUtils {

    private static Logger log = Logger.getLogger(FtpUtils.class.getClass());
    private static FTPClient ftpClient;
    private static Ftp f = new Ftp();

    public static Ftp getFtp(){
        f.setIpAddr("10.2.100.146");
        f.setPort(2121);
        f.setUserName("ftpUser");
        f.setPwd("qwer");
        f.setPath("jf");//对应的文件夹下,如果多层“/”分隔即可
        return f;
    }
    /**
     * 获取ftp连接
     * @param f
     * @return
     * @throws Exception
     */
    public static boolean connectFtp(Ftp f) throws Exception {
        ftpClient = new FTPClient();
        boolean flag = false;
        int reply;
        if (f.getPort() == null) {
            ftpClient.connect(f.getIpAddr(), 21);
        } else {
            ftpClient.connect(f.getIpAddr(), f.getPort());
        }
        ftpClient.login(f.getUserName(), f.getPwd());
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            return flag;
        }
        ftpClient.makeDirectory(f.getPath());
        ftpClient.changeWorkingDirectory(f.getPath());
        flag = true;
        return flag;
    }

    /**
     * 关闭ftp连接
     */
    public static void closeFtp() {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ftp上传文件
     * @param f
     * @throws Exception
     */
    public static void upload(File f) throws Exception {
        if (f.isDirectory()) {
            ftpClient.makeDirectory(f.getName());
            ftpClient.changeWorkingDirectory(f.getName());
            String[] files = f.list();
            for (String fstr : files) {
                File file1 = new File(f.getPath() + "/" + fstr);
                if (file1.isDirectory()) {
                    upload(file1);
                    ftpClient.changeToParentDirectory();
                } else {
                    File file2 = new File(f.getPath() + "/" + fstr);
                    FileInputStream input = new FileInputStream(file2);
                    ftpClient.storeFile(file2.getName(), input);
                    input.close();
                }
            }
        } else {
            File file2 = new File(f.getPath());
            FileInputStream input = new FileInputStream(file2);
            ftpClient.storeFile(file2.getName(), input);
            input.close();
        }
    }


    /**
     * 下载指定目录下所有文件(暂时不用)
     * fileName ,要下载文件的名称
     * localpath,本地的存储路径
     */
    public static boolean downloadAllFile(Ftp myFtp , String fileName, String localpath) {
        boolean issuccess = false;
        OutputStream out = null;
        InputStream in = null;
        try {
            FtpUtils.connectFtp(myFtp);
            //下载单个文件
           /* File localFile = new File(localpath.concat(File.separator).concat(fileName));
            out = new FileOutputStream(localFile);
            in = ftpClient.retrieveFileStream(fileName);
            byte[] byteArray = new byte[4096];
            int read = 0;
            while ((read = in.read(byteArray)) != -1) {
                out.write(byteArray, 0, read);
            }*/

            //下载目录下的所有文件
            /*FTPFile[] fs = ftpClient.listFiles();
            if (fs.length < 1) {
                log.info("下载目录为空,未下载到任何文件");
                return issuccess;
            }
            for (int i = 0; i < fs.length; i++) {
                FTPFile ff = fs[i];
                String outFileName = ff.getName();
                // 创建本地的文件时候要把编码格式转回来
                // String localFileName = new
                // String(ff.getName().getBytes("ISO-8859-1"), "UTF-8");
                File localFile = new File(localpath.concat(File.separator).concat(outFileName));
                out = new FileOutputStream(localFile);
                in = ftpClient.retrieveFileStream(outFileName);
                byte[] byteArray = new byte[4096];
                int read = 0;
                while ((read = in.read(byteArray)) != -1) {
                    out.write(byteArray, 0, read);
                }
                // 这句很重要 要多次操作这个ftp的流的通道,要等他的每次命令完成
                ftpClient.completePendingCommand();*/
                issuccess = true;
                log.info("成功下载一个文件{}"+fileName);
            //}
        } catch (Exception e) {
            log.info("FTP下载文件异常{}");
        } finally {
            try {
                if (out != null) {
                    out.flush();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                if (ftpClient != null) {
                    ftpClient.logout();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            if (null != out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return issuccess;
    }

    /**
     * 将文件名转为随机文件名(带后缀)
     * @return
     */
    public static String getFileName(){
        return String.valueOf(System.currentTimeMillis());
    }

    /**
     * 新文件名的路径
     * @param path
     * @param newFleName
     * @return
     */
    public  static String getNewPath(String path,String newFleName){
        return path.substring(0,path.lastIndexOf("\\"))+"\\"+ newFleName + path.substring(path.lastIndexOf("."));
    }

    public static void testupLoad() throws Exception {
        Ftp f = FtpUtils.getFtp();

        FtpUtils.connectFtp(f);
        String savePath = "C:\\Users\\李志鹏\\Desktop\\V1\\10.jpg";
        String imgBase64 = Base64ToImgeUtils.getImageStr("C:\\Users\\李志鹏\\Desktop\\123.jpg");
        Boolean isSuccess = Base64ToImgeUtils.generateImage(imgBase64,savePath);
        if(!isSuccess){
            System.out.println("转换文件失败。。。。");
        }
        File file = new File(savePath);
        //更改文件名称
        String newFileName = getFileName();
        File newFile = new File(getNewPath(savePath,newFileName));
        file.renameTo(newFile);

        FtpUtils.upload(newFile);//把文件上传在ftp上
        FtpUtils.closeFtp();
        log.info("上传文件完成。。。。地址为:http://10.2.100.146:8081/jf/"+ newFileName+savePath.substring(savePath.lastIndexOf(".")));
    }

    public void testDownload() throws Exception {
        Ftp f = new Ftp();
        f.setIpAddr("10.2.100.146");
        f.setPort(2121);
        f.setUserName("ftpUser");
        f.setPwd("qwer");
        f.setPath("jf/2020-08-21");
        downloadAllFile(f,"456.jpg","C:\\Users\\李志鹏\\Desktop\\V1\\");
    }

    public static void main(String[] args) throws Exception {
        testupLoad();
    }

}

package com.wonders.ftp.constroller;
import java.io.*;
import java.util.Scanner;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64ToImgeUtils {

    /**
     *  //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
     */
    public static String getImageStr(String imgePath)
    {
        String imgFile = imgePath;//待处理的图片
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(File2byte(new File(imgePath)));//返回Base64编码过的字节数组字符串
    }

    //base64字符串转化成图片
    public static boolean generateImage(String imgStr,String savePath)
    {   //对字节数组字符串进行Base64解码并生成图片
        if(imgStr == null) { //图像数据为空
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            String imgFilePath = savePath;//新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    /**
     * 将文件转换成byte数组
     * @param tradeFile
     * @return
     */
    public static byte[] File2byte(File tradeFile){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }
}

package com.wonders.ftp.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Ftp {
    private String ipAddr;//ip地址

    private Integer port;//端口号

    private String userName;//用户名

    private String pwd;//密码

    private String path;//aaa路径
}

### set log levels ###
log4j.rootLogger = DEBUG,Console,File

###  输出到控制台  ###
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%d{yy/MM/dd HH:mm:ss:SSS}]-%l:%m%n

### 输出到日志文件 ###
log4j.appender.File=org.apache.log4j.RollingFileAppender
log4j.appender.File.File=${project}src\\main\\resources\\log\\app.log
log4j.appender.File.MaxFileSize=10MB
log4j.appender.File.Threshold=ALL
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n

项目结构
FTP上传的结果:
在这里插入图片描述
本博客仅供学习交流,文中用到的链接以及部分内容来自互联网,侵权立删!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值