`
Franciswmf
  • 浏览: 797157 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

org.apache.commons.net.ftp.FTPClient上传下载压缩图片

 
阅读更多
org.apache.commons.net.ftp.FTPClient上传下载文件

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.xml.security.exceptions.Base64DecodingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.xxx.framework.exception.BusinessException;

/**
 * FTP 上传工具
 */
@Component
public class FtpFileUtils {
    private static final Logger     logger            = LoggerFactory.getLogger(FtpFileUtils.class);
    private static final FTPClient  client            = new FTPClient();
    @Value("${xxx.ftp.server}")
    private String                  ftpServer;
    @Value("${xxx.ftp.port}")
    private Integer                 ftpPort;
    @Value("${xxx.ftp.username}")
    private String                  username;
    @Value("${xxx.ftp.password}")
    private String                  password;
    @Value("${xxx.ftp.save.path}")
    private String                  directoryPrefix;// 比如/var/query/up/hopp


    /**
     * 连接服务器
     * 
     * @throws BusinessException
     */
    public void connect() throws BusinessException {
        try {
            client.connect(ftpServer, ftpPort);
        } catch (Exception e) {
            throw new BusinessException("connect to ftp server[" + ftpServer + "] fail", e);
        }
        try {
            logger.info("start to login ftp server");
            client.login(username, password);
            if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
                throw new BusinessException("fail login ftp server");
            }
            logger.info("login ftp server success");
            client.changeWorkingDirectory("/");
            logger.info("change ftp server working directory");
            client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
            client.setFileType(FTP.BINARY_FILE_TYPE);
            client.setControlEncoding("UTF-8");
        } catch (IOException e) {
            throw new BusinessException("login to ftp server[" + ftpServer + "] fail", e);
        }
    }

    /**
     * 上传文件file
     * @param directory
     * @param fileName
     * @param content
     * @throws BusinessException
     */
    public void uploadOneFile(String middleDirectory, String fileName, byte[] content) throws BusinessException {
    	uploadMethodOne(directoryPrefix,middleDirectory, fileName, new ByteArrayInputStream(content));
    }
    
   /**
    * 上传单个文件
    * xxx/hopp/"+entity.getId()+"/
    * @param directoryPreffix
    * @param directorySuffix
    * @param fileName
    * @param inputStream
    * @throws BusinessException
    */
    public void uploadMethodOne(String directoryPreffix,String directorySuffix, String fileName, InputStream inputStream) throws BusinessException {
        try {
        	connect();    
        	logger.info("FTP上传开始");
            //根据路径逐层判断目录是否存在,如果不存在则创建(mkd 一次创建多级目录没有得到预期效果)
            //1.首先进入ftp的根目录
            client.changeWorkingDirectory(directoryPreffix);
	        String[] dirs = directorySuffix.split("/");
	        for (String dir : dirs) {
	        	//2.创建并进入不存在的目录
	        	if (!client.changeWorkingDirectory(dir)) {
	        		client.mkd(dir);
	        		client.changeWorkingDirectory(dir);
	        	}
	        }
	        logger.info("上传图片:"+directoryPreffix +"/"+directorySuffix + "/" + fileName);
            client.storeFile(directoryPreffix +"/"+ directorySuffix + "/" + fileName, inputStream);
            logger.info("FTP上传结束");
        } catch (Exception e) {
            throw new BusinessException("upload fail", e);
        } finally {
            try {
                logger.info("close the ftp server connect");
                client.disconnect();
            } catch (IOException e) {
                throw new BusinessException("close connect fail", e);
            }
        }
    }
    
   /**
    * 上传多个文件
    * @param directoryPreffix,形如:/var/query/up/hopp
    * @param directorySuffix,形如:xxx/hopp/45/
    * @param fileMap,形如map:{img_1.jpg ,fileInputStream }
    * @throws BusinessException
    */
    public void uploadMultiFiles(String directoryPreffix,String directorySuffix, Map<String, Object> fileMap) throws BusinessException {
    	try {
        	connect();    
        	logger.info("FTP上传开始");
		//根据路径逐层判断目录是否存在,如果不存在则创建(mkd 一次创建多级目录没有得到预期效果)
		//1.首先进入ftp的根目录
		client.changeWorkingDirectory(directoryPreffix);
	        String[] dirs = directorySuffix.split("/");
	        for (String dir : dirs) {
	        	//2.创建并进入不存在的目录
	        	if (!client.changeWorkingDirectory(dir)) {
	        		client.mkd(dir);
	        		client.changeWorkingDirectory(dir);
	        	}
	        }
	        if(!fileMap.isEmpty()){
	        	int index=1;
	        	for (Entry<String, Object> entry : fileMap.entrySet()) {
					String fileName=directoryPreffix+"/"+directorySuffix+entry.getKey();
					InputStream fileInputStream=(InputStream) entry.getValue(); 
					logger.info("上传第"+(index++)+"个图片:"+fileName);
					client.storeFile(fileName, fileInputStream);
				}
	        }
	        logger.info("FTP上传结束");
        } catch (Exception e) {
            throw new BusinessException("upload fail", e);
        } finally {
            try {
                logger.info("close the ftp server connect");
                client.disconnect();
            } catch (IOException e) {
                throw new BusinessException("close connect fail", e);
            }
        }
    }

    
    /**
     * 根据图片路径下载
     * @param imgPath,形如:xxx/hopp/262/part_hopp_1.jpg
     * @return
     * @throws Exception
     */
    public synchronized byte[] downloadFileByImgPath(String imgPath) throws BusinessException {
    	//xxx/hopp/262/part_hopp_1.jpg
    	Integer idx=imgPath.lastIndexOf("/");
        byte[] resultByteArray = null;
        try {
            String directory = directoryPrefix + "/" + imgPath.substring(0, idx);
            String remoteFileName = directoryPrefix + "/" + imgPath;
            connect();
            client.changeWorkingDirectory(directory);
            logger.info(remoteFileName + "下载中...");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            boolean success = client.retrieveFile(remoteFileName, out);
            resultByteArray = out.toByteArray();
            logger.info(remoteFileName + "下载" + (success ? "成功" : "失败"));
        } catch (Exception e) {
            throw new BusinessException("图片" + imgPath + "下载失败", e);
        } finally {
            try {
				client.disconnect();
			} catch (IOException e) {
				throw new BusinessException("图片下载异常", e);
			}
            logger.info("disconnect success");
        }
        return resultByteArray;
    }
    
    /**
     * 下载文件
     * 
     * @param remoteFileName
     *            待下载文件名称
     * @param localDires
     *            下载到当地那个路径下
     * @param openId
     *            remoteFileName所在的路径
     * @return
     * @throws Exception
     */

    public synchronized byte[] downloadFileTwo(String type, String openId) throws Exception {
        byte[] resultByteArray = null;
        try {
            String directory = directoryPrefix + "/" + openId;
            String remoteFileName = directory + "/" + openId + "_" + type + ".jpg";
            connect();
            client.changeWorkingDirectory(directory);
            logger.info(remoteFileName + "开始下载....");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            boolean success = client.retrieveFile(remoteFileName, out);
            resultByteArray = out.toByteArray();
            logger.info(remoteFileName + "下载" + (success ? "成功" : "失败"));
        } catch (Exception e) {
            throw new RuntimeException("图片[" + openId + "][" + type + "]下载失败", e);
        } finally {
            client.disconnect();
            logger.info("disconnect success");
        }
        return resultByteArray;
    }
    
    /**
     * 压缩二进制图片数据
     * 大于10k时压缩,否则不压缩
     * @param base64
     * @return 
     * @throws Base64DecodingException
     */
    public static byte[] aaa(String base64Str){
		  byte[] base64BtArray= Base64.decodeBase64(base64Str);
		  float sizea = base64BtArray.length;  //byte[] 计算原图片大小
	      // 图片小于10kb,不需要压缩
	      float limitSize = 10 * 1024; // 图片大小上限
	      if(sizea <= limitSize){
	          return base64BtArray;
	      }
	      ByteArrayOutputStream os = new ByteArrayOutputStream();
	      try {
			Thumbnails.of(new ByteArrayInputStream(base64BtArray)).size(100,100).toOutputStream(os);
	      } catch (IOException e) {
			e.printStackTrace();
	      }
	      byte[] scaleResult = os.toByteArray();
	      return scaleResult;
	  }
    
    /**
     * 压缩二进制图片数据
     * 大于10k时压缩,否则不压缩
     * @param base64
     * @return 
     * @throws Base64DecodingException
     */
    public byte[] bbb(byte[] base64BtArray){
		  float sizea = base64BtArray.length;  //byte[] 计算原图片大小
	      // 图片小于10kb,不需要压缩
	      float limitSize = 10 * 1024; // 图片大小上限
	      if(sizea <= limitSize){
	          return base64BtArray;
	      }
		  ByteArrayOutputStream os = new ByteArrayOutputStream();
	      try {
			Thumbnails.of(new ByteArrayInputStream(base64BtArray)).size(100,100).toOutputStream(os);
	      } catch (IOException e) {
			e.printStackTrace();
		  }
	      byte[] scaleResult = os.toByteArray();
	      return scaleResult;
	  }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics