从ftp获取图片显示到jsp中

该博客主要讲述了如何从FTP服务器获取图片资源,并将这些图片成功地在JSP页面上进行展示的步骤和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


首先获取图片

获取图片

package com.gmt.action;

import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.gmt.ftp.util.ApacheFtpUtil;
import com.gmt.redis.UploadRedisManager;
import com.opensymphony.xwork2.ActionSupport;

public class ShowAtlasAction extends ActionSupport{

	private static final long serialVersionUID = 1L;
	
	private long imageId ; //图片的id
	private long folderId;//文件夹名
	
	public long getImageId() {
		return imageId;
	}

	public void setImageId(long imageId) {
		this.imageId = imageId;
	}

	public long getFolderId() {
		return folderId;
	}

	public void setFolderId(long folderId) {
		this.folderId = folderId;
	}
	
	public String viewImages(){
        ApacheFtpUtil.downFiles(folderId,imageId);
        return null;
	}
	//这个方法只适合查询少量的图片,少量不能大于ftp服务器连接的的最大值
	public String test(){
        ServletOutputStream output = null;
        InputStream input = null;
        try {
        	HttpServletResponse response = ServletActionContext.getResponse();
            input = ApacheFtpUtil.downFile(folderId,imageId);
            output = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte imageArray[] = new byte[4064];
			int len = 0;
			while((len = input.read(imageArray)) != -1){
				output.write(imageArray, 0, len);
			}
			output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	try {
        		if (input != null) {
        			input.close();
        		}
        		if (output != null) {
                	output.close();
        		}
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        }
        return null;
	}
	
	/**查询自制关卡*/
	public String showUpload(int id){
		ServletOutputStream output = null;
        try {
        	HttpServletResponse response = ServletActionContext.getResponse();
            output = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte [] uploadImageArray = UploadRedisManager.getUpLoadIMG(id);
			output.write(uploadImageArray);
			output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	try {
        		if (output != null) {
                	output.close();
        		}
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        }
		return null;
	}
	
}

调用从FTP获取图片的流的方法

package com.gmt.ftp.util;

import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.gmt.init.Key;
/**
 * 此类提供对完调用的方法
 * 
 * */

public class ApacheFtpUtil {
	
	public static void main(String args[]) throws Exception{  
	    //testUpload();  
	      //testDownload();  
	    FtpUtil ftpUtil=new FtpUtil();  
	    ftpUtil.connectServer("192.168.1.108", 2121, "admin", "admin", null);  
	    //获得ftp服务器上目录名称为DF4下的所有文件名称  
//	    List<String> list=ftpUtil.getFileList("/400000/");  
//	    System.out.println("文件名称列表为:"+list);  
	    //上传本地D盘文件aaa.txt到服务器,服务器上名称为bbb.txt  
//	    boolean back = ftpUtil.uploadFile("d:" + File.separator + "zbs.txt", "/DF4/zbshh.txt");
//	    System.out.println("上传是否成功="+back);
	    //从服务器上下载文件bbb.txt到本地d盘名称为ccc.txt  
	    
	    
//	    
//	    boolean back = ftpUtil.download("eee.txt", "d:" + File.separator + "fff.txt");  
//	    System.out.println("上传是否成功="+back);
//	    
	    
	    
	    //删除ftp服务器上文件:bbb.txt  
	    //ftpUtil.deleteFile("bbb.txt");
	    
	    
//	    boolean back = ftpUtil.createDirectory("20170327");
//	    System.out.println("创建目录成功="+back);
	} 
	
	/**
	 * 在ftp服务器上新建文件夹
	 * */
	public static boolean createDirectory(String dirPath){
		FtpUtil ftpUtil = new FtpUtil();  
		try {
			ftpUtil.connectServer(ftpip, ftpPort, ftpname, ftppassword, null);
			return ftpUtil.createDirectory(dirPath);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				ftpUtil.closeServer();
			} catch (IOException e) {
			}
			ftpUtil = null;
		}
		return false;
	}
	static String ftpip =  Key.getKey().getProperty("FTP_IP");
	static  int ftpPort =  Integer.valueOf(Key.getKey().getProperty("FTP_PORT"));
	static String ftpname = Key.getKey().getProperty("FTP_NAME");
	static String ftppassword =  Key.getKey().getProperty("FTP_PASSWORD");
	
	/**上传茬点
	 * name 文件的名称 
	 * address 上传的地址
	 * */
	public static boolean uploadAtlas(InputStream iStream ,String uploadPath){
		FtpUtil ftpUtil = new FtpUtil();  
		boolean bool = false;
		 try {
			ftpUtil.connectServer(ftpip, ftpPort, ftpname, ftppassword, null);
			//上传本地D盘文件aaa.txt到服务器,服务器上名称为bbb.txt  
			bool = ftpUtil.uploadAtlas(iStream, uploadPath);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				ftpUtil.closeServer();
			} catch (IOException e) {
			}
			ftpUtil = null;
		}  
		return bool;
	}
	
	/**获取上传茬点的名称*/
	public static List<String> getAtlasNameList(long atlasId){
		FtpUtil ftpUtil = new FtpUtil(); 
		List<String> atlasNameList = new ArrayList<String>();
		try {
			ftpUtil.connectServer(ftpip, ftpPort, ftpname, ftppassword, null);
			atlasNameList = ftpUtil.getFileList("/"+atlasId+"/");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return atlasNameList;
	}
	
	/**获取茬点图片的流
	 * 这个方法只适合查询少量的图片,少量不能大于ftp服务器连接的的最大值
	 * 这个方法没有关闭ftp连接
	 * */
	public static InputStream downFile(long atlasId,long imageId){
		FtpUtil ftpUtil = new FtpUtil(); 
		InputStream input = null;
		try {
			ftpUtil.connectServer(ftpip, ftpPort, ftpname, ftppassword, null);
			String path = "/"+atlasId+"/"+imageId+".png";
			System.out.println(path);
			input = ftpUtil.downFile(path);
			return input;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**获取茬点图片的流*/
	public static InputStream downFiles(long atlasId,long imageId){
		FtpUtil ftpUtil = new FtpUtil(); 
		InputStream input = null;
		ServletOutputStream output = null;
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			ftpUtil.connectServer(ftpip, ftpPort, ftpname, ftppassword, null);
			String path = "/"+atlasId+"/"+imageId+".png";
			System.out.println(path);
			input = ftpUtil.downFile(path);
            output = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte imageArray[] = new byte[4064];
			int len = 0;
			while((len = input.read(imageArray)) != -1){
				output.write(imageArray, 0, len);
			}
			output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	try {
        		if (input != null) {
        			input.close();
        		}
        		if (output != null) {
                	output.close();
        		}
        		ftpUtil.closeServer();
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        }
        return null;
	}
	
}

配置FTP

package com.gmt.ftp.util;

/** 
 * ftp登陆配置信息 
 * @author HarderXin 
 * 
 */  
public class FtpConfig {  
    //服务器地址名称  
    private String server;  
    //端口号  
    private int port;  
    //用户名称  
    private String username;  
    //密码  
    private String password;  
    //工作目录  
    private String location;  
     
    public String getServer() {  
        return server;  
    }  
  
    public void setServer(String server) {  
        this.server = server;  
    }  
  
    public int getPort() {  
        return port;  
    }  
  
    public void setPort(int port) {  
        this.port = port;  
    }  
  
    public String getUsername() {  
        return username;  
    }  
  
    public void setUsername(String username) {  
        this.username = username;  
    }  
  
    public String getPassword() {  
        return password;  
    }  
  
    public void setPassword(String password) {  
        this.password = password;  
    }  
  
    public String getLocation() {  
        return location;  
    }  
  
    public void setLocation(String location) {  
        this.location = location;  
    }  
}  

连接FTP数据库

package com.gmt.ftp.util;

import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.net.SocketException;  
import java.util.ArrayList;  
import java.util.List;  
  
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.FTPFileFilter;  
    
public class FtpUtil {    
    private FTPClient ftpClient;    
    public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;    
    public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;    
        
    /** 
     * 利用FtpConfig进行服务器连接 
     * @param ftpConfig 参数配置Bean类 
     * @throws SocketException 
     * @throws IOException 
     */  
    public void connectServer(FtpConfig ftpConfig) throws SocketException,    
            IOException {    
        String server = ftpConfig.getServer();    
        int port = ftpConfig.getPort();    
        String user = ftpConfig.getUsername();    
        String password = ftpConfig.getPassword();    
        String location = ftpConfig.getLocation();    
        connectServer(server, port, user, password, location);    
    }    
        
    /** 
     * 使用详细信息进行服务器连接 
     * @param server:服务器地址名称 
     * @param port:端口号 
     * @param user:用户名 
     * @param password:用户密码 
     * @param path:转移到FTP服务器目录  
     * @throws SocketException 
     * @throws IOException 
     */  
    public void connectServer(String server, int port, String user,    
            String password, String path) throws SocketException, IOException {    
        ftpClient = new FTPClient();    
        ftpClient.connect(server, port);    
        System.out.println("Connected to " + server + ".");    
        //连接成功后的回应码  
        System.out.println(ftpClient.getReplyCode());    
        ftpClient.login(user, password);    
        if (path!=null&&path.length() != 0) {    
            ftpClient.changeWorkingDirectory(path);    
        }    
        ftpClient.setBufferSize(1024);//设置上传缓存大小  
        ftpClient.setControlEncoding("UTF-8");//设置编码  
        ftpClient.setFileType(BINARY_FILE_TYPE);//设置文件类型  
    }    
      
    /** 
     * 设置传输文件类型:FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE   
     * 二进制文件或文本文件 
     * @param fileType 
     * @throws IOException 
     */  
    public void setFileType(int fileType) throws IOException {    
        ftpClient.setFileType(fileType);    
    }    
    
    /** 
     * 关闭连接 
     * @throws IOException 
     */  
    public void closeServer() throws IOException {    
        if (ftpClient!=null&&ftpClient.isConnected()) {    
            ftpClient.logout();//退出FTP服务器   
            ftpClient.disconnect();//关闭FTP连接   
        }    
    }  
      
    /** 
     * 转移到FTP服务器工作目录 
     * @param path 
     * @return 
     * @throws IOException 
     */  
    public boolean changeDirectory(String path) throws IOException {    
        return ftpClient.changeWorkingDirectory(path);    
    }    
      
    /** 
     * 在服务器上创建目录 
     * @param pathName 
     * @return 
     * @throws IOException 
     */  
    public boolean createDirectory(String pathName) throws IOException {    
        return ftpClient.makeDirectory(pathName);    
    }    
      
    /** 
     * 在服务器上删除目录 
     * @param path 
     * @return 
     * @throws IOException 
     */  
    public boolean removeDirectory(String path) throws IOException {    
        return ftpClient.removeDirectory(path);    
    }    
        
    /** 
     * 删除所有文件和目录 
     * @param path 
     * @param isAll true:删除所有文件和目录 
     * @return 
     * @throws IOException 
     */  
    public boolean removeDirectory(String path, boolean isAll)    
            throws IOException {    
            
        if (!isAll) {    
            return removeDirectory(path);    
        }    
    
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);    
        if (ftpFileArr == null || ftpFileArr.length == 0) {    
            return removeDirectory(path);    
        }    
        //     
        for (FTPFile ftpFile : ftpFileArr) {    
            String name = ftpFile.getName();    
            if (ftpFile.isDirectory()) {    
                System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");                 
                removeDirectory(path + "/" + name, true);    
            } else if (ftpFile.isFile()) {    
                System.out.println("* [sF]Delete file ["+path + "/" + name+"]");                            
                deleteFile(path + "/" + name);    
            } else if (ftpFile.isSymbolicLink()) {    
    
            } else if (ftpFile.isUnknown()) {    
    
            }    
        }    
        return ftpClient.removeDirectory(path);    
    }    
      
    /** 
     * 检查目录在服务器上是否存在 true:存在  false:不存在 
     * @param path 
     * @return 
     * @throws IOException 
     */  
    public boolean existDirectory(String path) throws IOException {    
        boolean flag = false;    
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);    
        for (FTPFile ftpFile : ftpFileArr) {    
            if (ftpFile.isDirectory()    
                    && ftpFile.getName().equalsIgnoreCase(path)) {    
                flag = true;    
                break;    
            }    
        }    
        return flag;    
    }    
    
    /** 
     * 得到文件列表,listFiles返回包含目录和文件,它返回的是一个FTPFile数组 
     * listNames():只包含目录的字符串数组 
     * String[] fileNameArr = ftpClient.listNames(path);  
     * @param path:服务器上的文件目录:/DF4 
     */  
    public List<String> getFileList(String path) throws IOException {    
        FTPFile[] ftpFiles= ftpClient.listFiles(path);    
        //通过FTPFileFilter遍历只获得文件  
/*      FTPFile[] ftpFiles2= ftpClient.listFiles(path,new FTPFileFilter() { 
            @Override 
            public boolean accept(FTPFile ftpFile) { 
                return ftpFile.isFile(); 
            } 
        });  */  
        List<String> retList = new ArrayList<String>();    
        if (ftpFiles == null || ftpFiles.length == 0) {    
            return retList;    
        }    
        for (FTPFile ftpFile : ftpFiles) {    
            if (ftpFile.isFile()) {    
                retList.add(ftpFile.getName());    
            }    
        }    
        return retList;    
    }    
    
    /** 
     * 删除服务器上的文件 
     * @param pathName 
     * @return 
     * @throws IOException 
     */  
    public boolean deleteFile(String pathName) throws IOException {    
        return ftpClient.deleteFile(pathName);    
    }    
    
    /** 
     * 上传文件到ftp服务器 
     * 在进行上传和下载文件的时候,设置文件的类型最好是: 
     * ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE) 
     * localFilePath:本地文件路径和名称 
     * remoteFileName:服务器文件名称 
     */  
    public boolean uploadFile(String localFilePath, String remoteFileName)    
            throws IOException {    
        boolean flag = false;    
        InputStream iStream = null;    
        try {    
            iStream = new FileInputStream(localFilePath);    
            //我们可以使用BufferedInputStream进行封装  
            //BufferedInputStream bis=new BufferedInputStream(iStream);  
            //flag = ftpClient.storeFile(remoteFileName, bis);   
            flag = ftpClient.storeFile(remoteFileName, iStream);    
        } catch (IOException e) {    
            flag = false;    
            return flag;    
        } finally {    
            if (iStream != null) {    
                iStream.close();    
            }    
        }    
        return flag;    
    } 
    
    /** 
     * 上传文件到ftp服务器 
     * 在进行上传和下载文件的时候,设置文件的类型最好是: 
     * ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE) 
     * localFilePath:本地文件路径和名称 
     * remoteFileName:服务器文件名称 
     */  
    public boolean uploadAtlas(InputStream iStream, String remoteFileName)    
            throws IOException {    
        boolean flag = false;     
        try {    
            flag = ftpClient.storeFile(remoteFileName, iStream);    
        } catch (IOException e) {    
            flag = false;    
            return flag;    
        } finally {    
            if (iStream != null) {    
                iStream.close();    
            }    
        }    
        return flag;    
    } 
    
    /** 
     * 上传文件到ftp服务器,上传新的文件名称和原名称一样 
     * @param fileName:文件名称 
     * @return 
     * @throws IOException 
     */  
    public boolean uploadFile(String fileName) throws IOException {    
        return uploadFile(fileName, fileName);    
    }    
    
    /** 
     * 上传文件到ftp服务器 
     * @param iStream 输入流 
     * @param newName 新文件名称 
     * @return 
     * @throws IOException 
     */  
    public boolean uploadFile(InputStream iStream, String newName)    
            throws IOException {    
        boolean flag = false;    
        try {    
            flag = ftpClient.storeFile(newName, iStream);    
        } catch (IOException e) {    
            flag = false;    
            return flag;    
        } finally {    
            if (iStream != null) {    
                iStream.close();    
            }    
        }    
        return flag;    
    }    
    
    /** 
     * 从ftp服务器上下载文件到本地 
     * @param remoteFileName:ftp服务器上文件名称 
     * @param localFileName:本地文件名称 
     * @return 
     * @throws IOException 
     */  
    public boolean download(String remoteFileName, String localFileName)    
            throws IOException {    
        boolean flag = false;    
        File outfile = new File(localFileName);    
        OutputStream oStream = null;    
        try {    
            oStream = new FileOutputStream(outfile);    
            //我们可以使用BufferedOutputStream进行封装  
            //BufferedOutputStream bos=new BufferedOutputStream(oStream);  
            //flag = ftpClient.retrieveFile(remoteFileName, bos);   
            flag = ftpClient.retrieveFile(remoteFileName, oStream);    
        } catch (IOException e) {    
            flag = false;    
            return flag;    
        } finally {    
            oStream.close();    
        }    
        return flag;    
    }    
        
    /** 
     * 从ftp服务器上下载文件到本地 
     * @param sourceFileName:服务器资源文件名称 
     * @return InputStream 输入流 
     * @throws IOException 
     */  
    public InputStream downFile(String sourceFileName) throws IOException {   
    	return ftpClient.retrieveFileStream(sourceFileName);  
    }    
      
}  

struts.xml配置Action

 <action name="showAtlasAction" class="com.gmt.action.ShowAtlasAction" method="viewImages">
		</action>

在jsp页面展示图片

<img src="showAtlasAction.action?imageId=<%=imageId%> & folderId=<%=atlasId%> & response=<%=response%>"
						alt="<%=atlasName%>" width="100" height="118" align="middle" calss="imgs">

注释:atlasId,imageId,response.atlasName  都是传的参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值