DownloadImageTool - sarasayhi/hello-world GitHub Wiki

import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;

import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.regex.Pattern;

public class DownloadImageTool { private final static Log logger = LogFactory.getLog(DownloadImageTool.class);

public static byte[] get(int imageType, String imageUrl, String enCode) throws Exception {
	byte[] fileData = null;
	if(StringUtils.isNotBlank(imageUrl)){
		if(1 == imageType){
			fileData = getBytes(imageUrl);
		}else{
			enCode = StringUtils.defaultIfBlank(enCode, "UTF-8");
			fileData = getBytes(imageUrl,enCode);
		}
	}
	return fileData;
}


/**
 * 文件名字获取文件二进制流
 * @author luofan 2016年8月17日 下午7:17:08
 */
public static byte[] getBytes(String fileName) throws Exception{
	byte[] filedata = null;
	FileInputStream fin = null;
	ByteArrayOutputStream outStream = null;
	try{
		File file = new File(fileName);
		fin = new FileInputStream(file);
		outStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int count = 0;
		while((count = fin.read(data, 0, 1024)) > 0){
			outStream.write(data, 0, count);
		}
		filedata = outStream.toByteArray();
	}catch(Exception e){
		logger.error("I/O流异常",e);
		throw new Exception();
	}finally {
		if(null!=outStream){
			outStream.close();
		}
		
		if(null!=fin){
			fin.close();
		}
	}
	return filedata;
}


/**
 * http协议获取二进制文件流
 * @author luofan 2016年7月30日 下午3:59:28
 */
public static byte[] getBytes(String imageUrl,String enCode) throws Exception{
	byte[] filedata = null;
	ByteArrayOutputStream outStream = null;
	InputStream is = null;
	try{
		System.setProperty("file.encoding", enCode);
		URL url = new URL(imageUrl);
		URLConnection conn = url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
		conn.setDoInput(true);
		conn.connect();
		outStream = new ByteArrayOutputStream();
		is = conn.getInputStream();
		byte[] data = new byte[1000];
		int count = -1;
		while((count = is.read(data, 0, 1000)) != -1){
			outStream.write(data, 0, count);
		}
		filedata = outStream.toByteArray();
		logger.info("===============文件流文件为:"+filedata.length);
	}catch(Exception e){
		logger.error("I/O流异常",e);
		throw new Exception();
	}finally {
		if(null!=outStream){
			outStream.close();
		}
		
		if(null!=is){
			is.close();
		}
	}
	return filedata;
}


/**
 * 判断导出图片名称是否含有非法字符
 * @param str
 */
public static String filenameFilter(String str) {  
	Pattern filePattern = Pattern.compile("[\\\\/:*?\"<>|#?]");  
    return str==null?null:filePattern.matcher(str).replaceAll("");  
}  

// /** // * ftp协议获取二进制文件流 // * @param IP // * @param userName // * @param passWord // * @return // * @throws Exception // */ // public static byte[] ftpGetBytes(String imageUrl){ // logger.info("图片的全路径:"+imageUrl); // FTPClient ftp = null; // byte[] filedata = null; // InputStream is = null; // ByteArrayOutputStream outStream = null; // try { // //组装ftp需要的参数 // imageUrl = URLDecoder.decode(imageUrl, "UTF-8"); // logger.info("图片的全路径:"+imageUrl); // String[] users = imageUrl.substring(6, imageUrl.indexOf("@")).split(":"); // String userName = users[0]; // String password = users[1]; // String ip = imageUrl.substring(imageUrl.indexOf("@")+1,imageUrl.length()); // String path = ip.substring(ip.indexOf("/")+1, ip.lastIndexOf("/")); // ip = ip.substring(0,ip.indexOf("/")); // String fileName = imageUrl.substring(imageUrl.lastIndexOf("/")+1,imageUrl.length()); // fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1"); // logger.info("ftp解析的参数:{"+userName+"},{"+password+"},{"+ip+"},{"+path+"},{"+fileName+"}"); // // //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 // ftp = new FTPClient(); // int reply; // ftp.connect(ip); // ftp.setBufferSize(1024); // ftp.setControlEncoding("UTF-8"); // ftp.setFileType(FTP.BINARY_FILE_TYPE); // ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE); // Boolean loginFlag = false; // loginFlag = ftp.login(userName, password);//登录 // reply = ftp.getReplyCode(); // ftp.changeWorkingDirectory(path); // // File localFile = new File("D:\123.jpg"); // OutputStream os = new FileOutputStream(localFile); // ftp.retrieveFile(fileName, os); // // if (loginFlag && FTPReply.isPositiveCompletion(reply)){ // outStream = new ByteArrayOutputStream(); // is = ftp.retrieveFileStream(fileName); // if(is!=null){ // byte[] data = new byte[1024]; // int count = 0; // while((count = is.read(data, 0, 1024)) > 0){ // outStream.write(data, 0, count); // } // filedata = outStream.toByteArray(); // } // } // // logger.info("===============文件流文件为:"+filedata.length); // } catch (Exception e) { // logger.error("ftp获取文件异常",e); // }finally { // // if(outStream!=null){ // try{ // outStream.close(); // } // catch (IOException ioe){ // logger.error("I/O流异常",ioe); // } // } // // if(is!=null){ // try{ // is.close(); // } // catch (IOException ioe){ // logger.error("I/O流异常",ioe); // } // } // // if (ftp != null){ // try{ // ftp.logout(); // } // catch (IOException ioe){ // logger.error("I/O流异常",ioe); // } // } // // if (ftp.isConnected()){ // try{ // ftp.disconnect(); // } // catch (IOException ioe){ // logger.error("I/O流异常",ioe); // } // } // // } // return filedata; // }

// public static byte[] ftpGetBytes(String imageUrl){ // InputStream is = null; // ByteArrayOutputStream outStream = null; // byte[] filedata = null; // try{ // imageUrl = URLDecoder.decode(imageUrl, "UTF-8"); // System.setProperty("file.encoding", "UTF-8"); // logger.info("===============原始文件路径:"+imageUrl); // URL url = new URL(imageUrl);
// is = url.openConnection().getInputStream(); // byte[] buffer = new byte[4096]; // outStream = new ByteArrayOutputStream(); // int count = 0; // while ((count = is.read(buffer)) > 0) { // outStream.write(buffer, 0, count); // } // filedata = outStream.toByteArray(); // outStream.flush(); // logger.info("===============文件流文件为:"+filedata.length); // }catch(Exception e){ // logger.error("ftp获取文件异常",e); // }finally{ // if(outStream!=null){ // try{ // outStream.close(); // } // catch (IOException ioe){ // logger.error("I/O流异常",ioe); // } // } // // if(is!=null){ // try{ // is.close(); // } // catch (IOException ioe){ // logger.error("I/O流异常",ioe); // } // } // } // return filedata; // } // // // }