JavaWeb 如何从FTP服务器下载文件 页面如何获取到FTP服务器上的图片进行显示

前几天,写了一篇关于如何上传图片保存至FTP服务器的文章,今天继续把上传到FTP服务器的图片下载下来,在页面中进行显示。也就是满足了我们日常代码demo中,页面需要动态加载的图片的实例的实现。(不再需要手动把图片保存在WebContent下static静态文件夹下哈哈哈,相信很多初学小伙伴为了实现这种效果都是这么干的)
要点:前端通过ajax提交请求、Controller层ftp服务器路径的获取、本地路径的设置。

1. html页面

<html>
<head>
<title>获取FTP服务器上的图片</title>
<meta charset="utf-8">
</head>
<body>
<div>
     <a onclick="details();">家庭成员情况</a>
</div>

<div>
    <table>
        <tr>
            <td>
                <label>男方照片:</label>
            </td>
            <td>
                <img id="boy"  alt="加载失败" height="50px" weight="50px" >
            </td>
        </tr>
        <tr>
            <td>
                <label>女方照片:</label>
            </td>
            <td>
                <img id="girl"  alt="加载失败" height="50px" weight="50px" >
            </td>
        </tr>
    </table>
</div>
<script type="text/javascript">
        function details() {
        var jtbm = document.getElementById("e_jt").value;
        $.ajax({
            type : 'POST',
            url : //请求controller的路径
            data : {jt : jtbm},
            success : function (d){

                //请求成功,给照片处可以用下面的方法给src属性赋值
                $("#boy").attr('src',d.map['boy']);
                $("#girl").attr('src',d.map['girl']);
            }
        })
    }
</script>
</body>
</html>

注意:Html代码中没有太多注意事项,完成一个请求就OK。

2.Controller层代码

看代码之前也看这么一个请求过程:
当你在浏览器点击 发起一个请求 后,服务器端此时并没有图片,它只有(或者是他只能读取到)你在数据库中保存的图片路径,它需要继续向ftp服务器发送请求,把图片下载到本地服务器(Tomcat),前端页面通过寻找Tomcat中下载后保存的路径,才能够在页面上展现。
当你在浏览器点击 发起一个请求 后,服务器端此时并没有图片,它只有(或者是他只能读取到)你在数据库中保存的图片路径,它需要继续向ftp服务器发送请求,把图片下载到本地服务器(Tomcat),前端页面通过寻找Tomcat中下载后保存的路径,才能够在页面上展现。


    @RequestMapping("你的请求路径")
    @ResponseBody
    public ResponseModel findOne(String jt, HttpServletRequest request) {
        //获取项目发布后的路径,该方法可以获取到根目录。
        localPath = request.getSession().getServletContext().getRealPath("");
        System.out.println(localPath);

        //ResponseModel是自己封装的一个SpringMVC aJax返回对象
        ResponseModel model = new ResponseModel();

            /*此部分代码为业务逻辑处理,目的是为了通过传过来的 jt 获取到对应的保存在数据库中的图片路径
              可忽略我的这部分代码,做你自己的逻辑处理,拿到图片路径即可
              因为数据库中图片我们都只是保存的图片路径,而不是图片!!!*/
            Object fms = daoHandler.findOne(FMSModel.class, jt);
            MraModel mra = new MraModel();
            Condition condition = new SimpleCondition();
            System.out.println("==============....=");
            condition.andEqual("JT_BH", jt);
            System.out.println("============....===");

            List<MraModel> list = (List<MraModel>) daoHandler.find(MraModel.class, condition);
            System.out.println(list.get(0).getJtbh());
            for(MraModel mm : list){
                System.out.println(mm.getNfsfzfj());
                boy = mm.getNfsfzfj();
                System.out.println(mm.getNvfsfzfj());
                girl = mm.getNvfsfzfj();
                break;
            }

            /*  业务逻辑处理结束 */
            /* 下面才是今天的重点 */
            //从ftp服务器下载图片到 -- 服务器

            //FtpConection为一个封装的工具类,下文可以看到代码
            FtpConection conection = new FtpConection(ftp服务器地址, ftp服务器端口, ftp服务器用户名, ftp服务器密码);

            Map<String,String> map = new HashMap<String,String>();
            //包含进文件名
            if(boy != null){ //boy 保存的是从数据库中读取到的路径值,和你前面的业务逻辑处理有关。

                String hPath = "\\tempfiles\\"+boy; //在发布到本地tomcat后中保存的路径
                String jsPath = "../../tempfiles/"+boy; //在前端页面取值时 的路径
                localPath = localPath+hPath; //完整的本地路径

                boolean flag = conection.downloadFile(boy, localPath);
                if (flag){
                    System.out.println("下载成功!");
                }else{
                    System.out.println("下载 error");
                }
                map.put("boy",jsPath);
            }
            if(girl != null){
                localPath = request.getSession().getServletContext().getRealPath("");
                String hPath = "\\tempfiles\\"+girl;
                String jsPath = "../../tempfiles/"+girl;
                localPath = localPath+hPath;
                System.out.println(localPath);
                boolean flag = conection.downloadFile(girl, localPath);
                if (flag){
                    System.out.println("下载成功!");
                }else{
                    System.out.println("下载 error");
                }
                map.put("girl",jsPath);
            }

            model.setObject(fms);
            model.setMap(map);
            model.success();
        } catch (Exception e) {
            e.printStackTrace();
            model.error(e.getMessage());
        }
        return model;
    }

注意:

**
- 1 request.getSession().getServletContext().getRealPath(“”)可以获取到项目发布后的路径,也就是为了 前端能顺利拿到图片,从ftp下载下来的图片必须保存在这个根目录下的某个文件夹
- 2 String hPath = “\tempfiles\”+boy; //在发布到本地tomcat后中保存的路径
String jsPath = “../../tempfiles/”+boy; //在前端页面取值时 的路径
hPath就是发布到本地tomcat下中的某个路径,但在windows系统中,路径中 使用 “\”,但在编译的项目中前端那图片路径中, 使用的是”/“。(注意这两个斜杠的方向)jsPath就是为了前台取值方便,直接通过jsPath就可以拿到值。
- 3 至于jsPath为什么写成 ../../这种形式,是因为发布后的项目,你当前的页面的位置和你保存的图片的位置不在同一个文件夹,通过 ../寻找上一级目录,然后走到保存图片的位置。
- 4 最后把图片路径通过map键值对返回到前端页面
**

3. 辅助工具类之FtpConection

/**
 * FTP服务器连接,用于访问FTP服务器,实现常用的创建目录、删除目录、上传文件、下载文件等操作。
 * @author qinhuan
 * @version 2013-03-01 17:13:39
 */
public class FtpConection {

    /**
     * 文件上次的缓存区大小
     */
    private static final int BUF_SIZE = 1024*1024;


    private Logger logger = LoggerFactory.getLogger(FtpConection.class);


    private String hostname;
    private Integer port;
    private String username;
    private String password;

    FTPClient client;

    /**
     * 创建一个与FTP服务器的连接。
     * @param url 服务器IP地址
     * @param prot 服务端口
     * @param username 用户名
     * @param password 密码
     */
    public FtpConection(String url, Integer prot, String username, String password) {
        this.hostname = url;
        this.port = prot;
        this.username = username;
        this.password = password;
        client = new FTPClient();
        try {
            client.connect(hostname, port);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FtpConection:链接FTP服务器发生异常!");
        }

        try {
            client.login(username, password);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FtpConection:登陆FTP服务器发生异常!");
        }
    }

    /**
     * 获得原始的FTPClient对象
     * @return FTPClient对象
     */
    public FTPClient getClient() {
        return client;
    }

    /**
     * 测试连接和登录是否成功
     * @return Boolean值,true-连接并登录成功,false-连接超时或登录失败。
     */
    public boolean isConnected() {
        boolean result = false;
        int reply = client.getReplyCode();
        String info = null;
        switch (reply) {
        case 0:
            info = "连接超时!";
            break;
        case 230:
            info = "连接成功,登陆成功!";
            result = true;
            break;
        case 530:
            info = "用户名或密码错误!";
            break;
        }
        logger.info(info);
        return result;
    }


    /**
     * 上传文件
     * @param localPath 本地文件路径(含文件名)
     * @param serverPath FTP服务器存储路径(含文件名)
     * @return Boolean值,true-上传成功,false-上传失败(文件存在或目录错误)。
     * @throws IOException
     */
    public boolean uploadFiles(String localPath, String serverPath) throws IOException {
        boolean result = false;

        client.setFileType(FTP.BINARY_FILE_TYPE);
        client.enterLocalPassiveMode();
        client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
        client.setBufferSize(BUF_SIZE);

        InputStream local = null;
        try {
            local = new FileInputStream(localPath);
            result = client.storeFile(serverPath, local);
        } finally {
            if (local != null) {
                local.close();
            }
        }

        return result;
    }


    /**
     * 利用流 上传文件
     * @param in 本地流
     * @param serverPath 服务器路径
     * @return True 文件上传成功,False 文件上传失败
     * @throws IOException
     */
    public boolean uploadFiles(InputStream in, String serverPath) throws IOException {
        boolean result = false;

        client.setFileType(FTP.BINARY_FILE_TYPE);
        client.enterLocalPassiveMode();
        client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
        client.setBufferSize(BUF_SIZE);

        InputStream local = null;
        try {
            local = in;
            result = client.storeFile(serverPath, local);
        } finally {
            if (local != null) {
                local.close();
            }
        }

        return result;
    }

    /**
     * 下载文件
     * @param serverPath FTP服务器文件路径(含文件名)
     * @param localPath 本地存储文件路径(含文件名)
     * @return Boolean值,true-下载成功,false-下载失败(文件目录不存在或文件不存在)。
     * @throws IOException
     */
    public boolean downloadFile(String serverPath, String localPath) throws IOException {
        boolean result = false;

        client.setFileType(FTP.BINARY_FILE_TYPE);
        client.enterLocalPassiveMode();
        client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
        client.setBufferSize(BUF_SIZE);

        OutputStream local = null;
        try {
            local = new FileOutputStream(localPath);
            result = client.retrieveFile(serverPath, local);
        } finally {
            try {
                local.close();
            } catch (Exception e) {
                // 本地目录不存在,下载失败。
                logger.error("FTP 下载文件在本地保存出现异常,本地路径不存在!");
                return false;
            }
        }

        return result;
    }


    /**
     * 退出已登录的FTP用户
     * @return Boolean值,true-退出成功,false-退出失败(连接为登录)。
     * @throws IOException
     */
    public boolean logout() throws IOException {
        return client.logout();
    }
}

5.辅助工具类之ResponseModel


/**
 * Spring MVC AJAX response 返回对象
 * 
 *
 */
public class ResponseModel implements Serializable {
    private static final long serialVersionUID = -446626533112009414L;

    public static final String EMSG_SYS_ERROR       = "服务器错误。";
    public static final String EMSG_SUCCESS         = "成功完成。";

    public static final String STATUS_SYS_ERROR         = "0";
    public static final String STATUS_SUCCESS           = "1";
    public static final String STATUS_NO_PERMISSIONS    = "2";
    public static final String STATUS_UNKNOW_INPUT      = "3";
    public static final String STATUS_NO_LOGIN          = "4";

    public static final String KEY_LIST     = "list";
    public static final String KEY_OBJECT   = "obj";
    public static final String KEY_MAP      = "map";


    /**
     * 服务器响应状态(0:服务器错误|1:正确完成|2:权限不足|3:未知输入数据)
     */
    private String status;
    /**
     * 服务器错误信息
     */
    private String emsg;
    /**
     * 服务器响应数据
     */
    private Map<String, Object> data;

    public ResponseModel() {
        super();
        data = new HashMap<String, Object>();
    }

    public ResponseModel(String status, String emsg) {
        this();
        this.status = status;
        this.emsg = emsg;
    }

    public String getStatus() {
        return status;
    }

    public String getEmsg() {
        return emsg;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public String getVersion() {
        return version;
    }

    @Override
    public String toString() {
        return "ResponseModel [status=" + status + ", emsg=" + emsg + ", data="
                + data + "]";
    }

    /**
     * 成功完成。
     */
    public ResponseModel success() {
        this.success(EMSG_SUCCESS);
        return this;
    }



    /**
     * 向返回Model中添加键/值数据。(默认调用success())
     * @param key
     * @param value
     */
    public void put(String key, Object value) {
        this.data.put(key, value);
        this.success();
    }

    /**
     * 向返回Model中添加键/值数据。
     * @param key
     * @param value
     * @param isSuccess 是否成功返回。
     */
    public void put(String key, Object value, boolean isSuccess) {
        this.data.put(key, value);
        if (isSuccess) {
            this.success();
        }
    }

    public Object get(String key) {
        return data.get(key);
    }


    /**
     * 向返回Model中添加对象。(使用默认的key[KEY_OBJECT],默认调用success()。)
     * @param obj
     */
    public void setObject(Object obj) {
        this.put(KEY_OBJECT, obj);
        this.success();
    }

    /**
     * 向返回Model中添加Map对象。(使用默认的key[KEY_MAP],默认调用success()。)
     * @param map
     */
    public void setMap(Map<?, ?> map) {
        this.put(KEY_MAP, map);
        this.success();
    }
}

至于你的项目发布后,各个文件夹的相对位置可以通过右键项目–》 Properties –》Deployment Assembly 查看
查看项目发布后的路径

原创文章,未经作者允许,严禁转载!
文章:如何上传文件图片至FTP 服务器

猜你喜欢

转载自blog.csdn.net/weixin_39609665/article/details/81604230