win7 ftp安装搭建,并且上传图片到ftp文件夹下,使用nginx访问下载图片

ftp服务器搭建,这是在服务器上搭建的,下面的上传代码功能是在另一台电脑上操作的,相当于是一台电脑往另一台电脑上传图片.

双击它进去

右键网站,添加ftp站点,下面的aaa是我新建好的.

我这个路径选择的是nginx下面的路径,后面上传图片到这个路径下,使用nginx直接就可以访问到了,这儿设置这个路径就相当于是两台电脑直接的共享文件夹.

这个ip是本机ip端口自定义就可以,21是ftp默认端口

这个填上面新创建的用户

就可以看到共享文件夹下面的东西了,如果让一直输入用户名密码的话,就重新回到创建用户那里重置一下密码.

右键编辑权限

上面新建的用户在user组下,把相应的读写权限加上,

上传图片,文件代码

导入依赖,我使用的是springcloud项目,自带MultipartFile包,如果没有这个包的导下就可以了.

       <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.3</version>
        </dependency>

创建配置文件 

#商品图片地址
commodityImgPath=commodity
#用户图片地址
userImgPath=user
#订单图片地址
orderImgPath=order

#ftp相关配置
FTP_ADDRESS=192.168.34.81
FTP_PORT=21
FTP_USERNAME=kxj
FTP_PASSWORD=123456
#下面这个默认不配就相当于是ftp服务器上的这个路径,就是创建ftp的时候选的那个共享路径C:/soft/nginx-1.14.2/nginx-1.14.2/commodity
FTP_BASEPATH=
#图片服务器相关配置,这个是nginx路径,当上传图片成功的时候,拼接一个图片路径的参数
IMAGE_BASE_URL=http://192.168.34.81:8888/

 

创建一个实体类,注入进来值,方便传参

package com.zy.zs.bean;

/**
 * @author kxj
 * @version 1.0
 * @date 2019/8/14 21:15
 */

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value={"classpath:all.properties"})
public class FTPBean {
    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;

    @Value("${FTP_PORT}")
    private String FTP_PORT;

    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;

    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;

    @Value("${FTP_BASEPATH}")
    private String FTP_BASEPATH;

    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;


    public String getFTP_ADDRESS() {
        return FTP_ADDRESS;
    }

    public void setFTP_ADDRESS(String FTP_ADDRESS) {
        this.FTP_ADDRESS = FTP_ADDRESS;
    }

    public String getFTP_PORT() {
        return FTP_PORT;
    }

    public void setFTP_PORT(String FTP_PORT) {
        this.FTP_PORT = FTP_PORT;
    }

    public String getFTP_USERNAME() {
        return FTP_USERNAME;
    }

    public void setFTP_USERNAME(String FTP_USERNAME) {
        this.FTP_USERNAME = FTP_USERNAME;
    }

    public String getFTP_PASSWORD() {
        return FTP_PASSWORD;
    }

    public void setFTP_PASSWORD(String FTP_PASSWORD) {
        this.FTP_PASSWORD = FTP_PASSWORD;
    }

    public String getFTP_BASEPATH() {
        return FTP_BASEPATH;
    }

    public void setFTP_BASEPATH(String FTP_BASEPATH) {
        this.FTP_BASEPATH = FTP_BASEPATH;
    }

    public String getIMAGE_BASE_URL() {
        return IMAGE_BASE_URL;
    }

    public void setIMAGE_BASE_URL(String IMAGE_BASE_URL) {
        this.IMAGE_BASE_URL = IMAGE_BASE_URL;
    }
}

 上传图片的工具类

package com.zy.zs.utils;

import com.zy.zs.bean.FTPBean;
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.*;

public class FtpUtil {
  
    /** 
     * ftp上传图片方法 
     *title:pictureUpload 
     *@param ftpConfig  由spring管理的FtpConfig配置,在调用本方法时,可以在使用此方法的类中通过@AutoWared注入该属性。由于本方法是静态方法,所以不能在此注入该属性 
     *@param picNewName 图片新名称--防止重名 例如:"1.jpg" 
     *@param picSavePath 图片保存路径。注:最后访问路径是 ftpConfig.getFTP_ADDRESS()+"/images"+picSavePath 
     *@param file 要上传的文件(图片) 
     *@return 若上传成功,返回图片的访问路径,若上传失败,返回null 
     * @throws
     */  
    public static String pictureUploadByConfig(FTPBean ftpConfig, String picNewName, String picSavePath, InputStream inputStream) throws IOException{
  
        String picHttpPath = null;  
  
  
        boolean flag = uploadFile(ftpConfig.getFTP_ADDRESS(), ftpConfig.getFTP_PORT(), ftpConfig.getFTP_USERNAME(),  
                ftpConfig.getFTP_PASSWORD(), ftpConfig.getFTP_BASEPATH(), picSavePath, picNewName, inputStream);  
  
        if(!flag){  
            return picHttpPath;  
        }  
  
        //picHttpPath = ftpConfig.getFTP_ADDRESS()+"/images"+picSavePath+"/"+picNewName;  
        picHttpPath = ftpConfig.getIMAGE_BASE_URL()+picSavePath+"/"+picNewName;  
        System.out.println("==="+picHttpPath);  
        return picHttpPath;  
    }  
      
      
      
      
    /**   
     * 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, String ftpPort, String username, String password, String basePath,    
            String filePath, String filename, InputStream input) {  
        int port = Integer.parseInt(ftpPort);  
        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();//这个设置允许被动连接--访问远程ftp时需要  
            //上传文件    
            if (!ftp.storeFile(filename, input)) {    
                return result;    
            }    
            input.close();    
            ftp.logout();    
            result = true;    
        } catch (Exception 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;    
    }    

    /** 
* Description: 从FTP服务器删除文件 
* @param url FTP服务器hostname 
* @param port FTP服务器端口 
* @param username FTP登录账号 
* @param password FTP登录密码 
* @param remotePath FTP服务器上的相对路径 
* @return 
*/  
public boolean delFile(String url, int port,String username, String password, String remotePath) {  
boolean success = false; 
    FTPClient ftp = new FTPClient();  
    try {  
        int reply; 
        ftp.connect(url, port); 
        //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
        ftp.login(username, password);//登录  
        reply = ftp.getReplyCode();  
        if (!FTPReply.isPositiveCompletion(reply)) {  
            ftp.disconnect();  
            return success;  
        }  
        ftp.deleteFile(remotePath); 
        ftp.logout();  
        success = true;  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        if (ftp.isConnected()) {  
            try {  
                ftp.disconnect();  
            } catch (IOException ioe) {  
            }  
        }  
    }  
    return success;  
} 
}  

 controller代码

    @RequestMapping("/insertCommodity2")
    @ResponseBody
    public ResultUtil<String> insertCommodity(HttpSession session,ProductDetails productDetails, MultipartFile productImg, MultipartFile[] productImgs, MultipartFile productDetailImg){

        String str1 = "null";
        //上传商品图片
        ResultUtil<String> stringResultUtil = uploadingImgs(commodityImgPath, productImg);
        if (stringResultUtil!=null){
            if (stringResultUtil.isSuccess()){
                str1 = stringResultUtil.getData();
            }else{
                return stringResultUtil;
            }
        }

        ResultUtil<Integer> integerResultUtil = zsCommodityFeign.insertCommodity(str1,str2,str3,productDetails);
       // ResultUtil<Integer> integerResultUtil = zsCommodityFeign.insertCommodity("1","2","3",productDetails);
        if (integerResultUtil.isSuccess()){
            return new ResultUtil<>(true,"添加成功!");
        }
        return new ResultUtil<>(false,"添加失败!");
    }


    /**
     * 上传图片操作,返回图片名称.
     * @param multipartFiles
     * @return
     */
    public ResultUtil<String> uploadingImgs(String url,MultipartFile... multipartFiles){

        String str = "";
        if(multipartFiles!=null&&multipartFiles.length>0){
            for (MultipartFile multipartFile:multipartFiles){
                if (!"".equals(multipartFile.getOriginalFilename())){
                    File file = new File(url);
                    if(!file.exists()){   //判断改目录是否存在不存在就创建
                        file.mkdirs();
                    }
                    String oriName = multipartFile.getOriginalFilename();  //获取到上传的时候的图片名
                    String endName = oriName.substring(oriName.lastIndexOf("."));  //获取到后缀名
                    //判断是否为图片
/*                if(!endName.matches(".+(.JPEG|.jpeg|.JPG|.jpg)$")){
                    return new ResultUtil<>(false,"请上传图片!");
                }*/
                    //如果图片超过512k返回false   自己定义
                /*if(multipartFile.getSize()>512*1024){
                    return new ResultUtil<>(false,"文件不支持>512KB!!");
                }*/
                    //重命名文件名   也可以使用UUID
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String format = simpleDateFormat.format(new Date());

                    //String picName = UUID.randomUUID().toString();  uuid生成的名字
                    String newName = oriName.substring(0,oriName.lastIndexOf("."))+"_"+format+endName;
                    //newName = newName.substring(0,newName.length()-4)+newName.substring(newName.length()-3,newName.length());
                    try {
                        String s = FtpUtil.pictureUploadByConfig(ftpBean, newName, commodityImgPath, multipartFile.getInputStream());//上传到图片服务器的操作
                        str+=s+"-";
                        // multipartFile.transferTo(new File(url+File.separator+newName));  //上传图片
                    } catch (IOException e) {
                        e.printStackTrace();
                        return new ResultUtil<>(false,"上传失败,详细信息为"+e.getMessage());
                    }
                }else{
                    return null;
                }
            }
            str = str.substring(0,str.length()-1);

            return new ResultUtil<>(true,str);
        }else{
            return null;
        }
    }

就是在原来本地上传图片的基础上把上传方法一换就可以了,换成往ftp上传,其余的代码都是自己写的业务逻辑没必要一样.然后运行上传就可以了,上传完成后,会返回一个字符串,就是上传图片的位置,根据配置文件中IMAGE_BASE_URL=http://192.168.34.81:8888/这个参数进行搭配,然后直接访问这个路径下面的图片名就可以访问图片了,然后走自己的业务逻辑就可以了.

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值