美文网首页
ftp图片上传下载方法

ftp图片上传下载方法

作者: 初心myp | 来源:发表于2019-04-29 16:19 被阅读0次

pom依赖

<!-- ftp -->
<dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>3.6</version>
</dependency>

Java代码

该代码提供一种上传方法和两种下载方法
下载第一种:使用流进行下载,下载之后响应一个地址,直接在浏览器访问下载
下载第二种:使用ftp客户端下载,下载到本地指定目录

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 org.apache.tomcat.util.http.fileupload.IOUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @FileName: FtpUtil
 * @Description: ftp工具类
 * @author: <a href="mailto: muyuanpei@camelotchina.com">myp</a>
 * @create: 2019-04-25 17:07
 * @Copyright: (c) 2018年 北京柯莱特科技有限公司
 */
@Slf4j
public class FtpUtil {

    private static final String host = "主机ip";
    private static final int port = 21;
    private static final String username = "ftpuser";
    private static final String password = "ftpuser";
    private static final String basePath = "/home/ftpuser/data/img";
    private static final String imageBaseUrl = "http://主机ip:9090/img";

    /**
    * <p>Discription: 文件上传</p>
    * Created on: 15:26 2019/4/29
    * @author muyuanpei
    * @param multipartFile 文件
    * @return Map<String, Object> 上传结果
    */
    public static Map<String, Object> uploadPic(MultipartFile multipartFile) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            //将图片重新命名
            //获取原始图片名称
            String oddName = multipartFile.getOriginalFilename();
            //获取原始图片扩展名
            String suffix = oddName.substring(oddName.lastIndexOf("."));
            //重新命名图片
            long time = new Date().getTime();
            String prefix = String.valueOf(CheckContainChinese.randCode()); //设置为随机数
            String newName = "file_" + prefix + "_" + time + suffix;
            //图片上传
            String filepath = new DateTime().toString("/yyyy/MM");
            boolean flag = FtpUtil.uploadFile(host, port, username, password, basePath, filepath , newName, multipartFile.getInputStream());
            if (flag) {
                resultMap.put("error", 0);
                resultMap.put("url", imageBaseUrl + filepath + "/" + newName);
            }else {
                resultMap.put("error", 1);
                resultMap.put("message", "图片上传失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("error", 1);
            resultMap.put("message", "图片上传发生异常!");
        }
        return resultMap;
    }


    /**
    * <p>Discription: 文件下载【使用http下载】</p>
    * Created on: 15:27 2019/4/29
    * @author muyuanpei
    * @param url1 文件地址
    * @param fileName 文件名称
    * @param response 响应体
    * @param request 请求体
    */
    public static void downloadPic(String url1, String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.reset(); //必要的清除response的缓存信息
        String[] strings = url1.split("/");
        URL url = new URL(url1);
        URLConnection conn = url.openConnection();
        conn.connect();
        HttpURLConnection httpconn = (HttpURLConnection) conn;
        int httpResult = httpconn.getResponseCode();
        if (httpResult != HttpURLConnection.HTTP_OK) {// 不等于HTTP_OK说明连接不成功
            log.error("\n http连接失败");
        } else {
            String queryString = request.getQueryString();
            String wd = strings[strings.length - 1];
            String decoded_wd = null;//解码后
            if (wd != null) {// wd不为空才进行解码
                if (!queryString.contains("%")) {// 不包含 % 就用 gbk 解码
                    decoded_wd = new String(wd.getBytes("iso-8859-1"), "gbk");
                } else { // 包含%分支 之有ie参数
                    String ie = request.getParameter("ie");
                    // 如果 ie 有值 且是受支持的,比如只能是utf-8和gbk
                    if ("utf-8".equals(ie) || "gbk".equals(ie)) {
                        decoded_wd = new String(wd.getBytes("iso-8859-1"), ie);
                    } else {// 包含%分支之,ie没有值, 或值不受支持
                        // 先用utf-8
                        decoded_wd = new String(wd.getBytes("iso-8859-1"), "utf-8");
                    }
                }
            }
            //设置文件名称
            if (StringUtils.isNotEmpty(fileName)) {
                decoded_wd = fileName;
            }
            InputStream in = conn.getInputStream();
            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("charset", "utf-8");
            response.addHeader("Pragma", "no-cache");
            String encodeName = URLEncoder.encode(decoded_wd, StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
            IOUtils.copy(in, response.getOutputStream());
        }
    }

    /**
     * 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服务器下载文件【使用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;
    }

}


相关文章

网友评论

      本文标题:ftp图片上传下载方法

      本文链接:https://www.haomeiwen.com/subject/kpzynqtx.html