packagecom.guttv.common.utils;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.net.HttpURLConnection;importjava.net.ProtocolException;importjava.net.URL;importjava.net.URLConnection;importjava.util.List;importjavax.servlet.http.HttpServletRequest;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.web.multipart.MultipartFile;importorg.springframework.web.multipart.MultipartHttpServletRequest;importcom.google.gson.Gson;importcom.guttv.common.utils.ZimgClient.ZimgResult;public classZimgClient {public static String zimgUrl = "http://192.168.1.221:4869/";public static String zimgShareUrl = "http://192.168.1.221:4869/";public static String tmpPath = "/var/guttv/logs/tmp";protected Logger logger =LoggerFactory.getLogger(getClass());public static voidmain(String[] args) {//从文件上传图片
ZimgResult ret0 = newZimgClient()
.uploadImg("/var/guttv/logs/tmp/gophercolor.png");
System.out.println(ret0.isRet()+ "\r\n" +ret0.getImageUrl());//从URL上传图片
ZimgResult ret = newZimgClient()
.uploadImgFromUrl("http://creatives.ftchinese.com/ads/beijing/201509/20150914_cartier_33660.gif");
System.out.println(ret.isRet()+ "\r\n" +ret.getImageUrl());//Send("http://192.168.1.221:4869/upload",//"c:/4c422e03jw1ejoqm5ghm0j20nl0fb76x.jpg", "jpg");
}/*** 从页面提交图片,上传到zimg
*
*@paramrequest
*@paramfileTag
*@return
*/
publicString uploadImgToZimg(HttpServletRequest request, String fileTag) {
String imgUrl= "";
MultipartHttpServletRequest mhs=(MultipartHttpServletRequest) request;
List files =mhs.getFiles(fileTag);if (files != null && files.size() > 0) {//上传到图片服务器
MultipartFile f = files.get(0);if (f.getSize() == 0)return "";
String tmpFileName= ZimgClient.tmpPath + "/"
+f.getOriginalFilename();//mkdir("./tmp")
File tmp = newFile(ZimgClient.tmpPath);
tmp.mkdir();
tmp= newFile(tmpFileName);try{//tmp.delete();
f.transferTo(tmp);
}catch(Exception e) {
e.printStackTrace();
}
ZimgResult ret= this.uploadImg(tmpFileName);
logger.debug(newGson().toJson(ret));if (ret != null &&ret.isRet())
imgUrl=ret.getImageUrl();//删除文件
if (tmp != null) {
tmp.setWritable(true);//try {//new FileOutputStream(tmp).close();//} catch (Exception e) {//e.printStackTrace();//}
System.gc();//java'bug,must be gc before delete
tmp.delete();
}
}returnimgUrl;
}/*** 指定文件名,上传到zimg
*
*@paramfileName
*@return
*/
publicZimgResult uploadImg(String fileName) {
String ext= "jpeg";int inx = fileName.lastIndexOf(".");if (inx > 0)
ext= fileName.substring(inx + 1);
String resp= this.Send(ZimgClient.zimgUrl + "upload", fileName, ext);return new Gson().fromJson(resp, ZimgResult.class);
}publicZimgResult uploadImgFromUrl(String url) {
String resp= this.SendFromUrl(url);return new Gson().fromJson(resp, ZimgResult.class);
}/*** 从指定的URL下载图片并上传到zimg服务器
*
*@paramzimgUrl
*@paramimgUrl
*@return
*/
protectedString SendFromUrl(String imgUrl) {//设置文件类型默认值
String ext = "jpeg";
String respXML= "";try{//获得connection对象
logger.debug("zimg server url:" +ZimgClient.zimgUrl);
URL zimgUL= newURL(ZimgClient.zimgUrl);
URLConnection zimgConnection=zimgUL.openConnection();
zimgConnection.setReadTimeout(50000);
zimgConnection.setConnectTimeout(25000);
HttpURLConnection zimgUC=(HttpURLConnection) zimgConnection;//设置HTTP协议的消息头
logger.debug("zimg set header");
zimgUC.setRequestMethod("POST");
zimgUC.setRequestProperty("Connection", "Keep-Alive");
zimgUC.setRequestProperty("Cache-Control", "no-cache");
zimgUC.setRequestProperty("Content-Type", ext.toLowerCase());//"jpeg");// zimgUC.setRequestProperty("COOKIE", "william");
zimgUC.setDoOutput(true);
zimgUC.setDoInput(true);
logger.debug("zimg connect server.");//与建立服务器连接
zimgUC.connect();//设置传输模式为二进制
logger.debug("zimg upload image in binary.");
OutputStream om=zimgUC.getOutputStream();//循环读取图片,发送到zimg服务器
ext= this.writeImage(imgUrl, om);
logger.debug("image type=" +ext);//byte[] buf = new byte[8192];//while (true) {//int len = in.read(buf);//if (len <= 0)//break;//om.write(buf, 0, len);//}//到开输入(返回信息)流
InputStreamReader im = newInputStreamReader(
zimgUC.getInputStream(),"UTF-8");//循环读取,知道结束,获取返回信息
logger.debug("zimg get response text.");char[] bb = new char[8192];while (true) {int length =im.read(bb);if (length == -1)break;char[] bc = new char[length];for (int i = 0; i < length; i++)
bc[i]=bb[i];
respXML+= newString(bc);
}
logger.debug("zimg response:" +respXML);//关闭上下行
im.close();
zimgUC.disconnect();
}catch(Exception e) {
logger.debug("zimg exception :" +e.getMessage());
e.printStackTrace();
}returnrespXML;
}/*** 返货图片类型
*
*@paramdata
*@return
*/
protected String getImageType(byte[] data) {
String type= null;//Png test:
if (data[1] == 'P' && data[2] == 'N' && data[3] == 'G') {
type= "PNG";returntype;
}//Gif test:
if (data[0] == 'G' && data[1] == 'I' && data[2] == 'F') {
type= "GIF";returntype;
}//JPG test:
if (data[6] == 'J' && data[7] == 'F' && data[8] == 'I'
&& data[9] == 'F') {
type= "JPG";returntype;
}returntype;
}/*** 获取URL的输入流
*
*@paramimgUrl
*@return
*/
privateString writeImage(String imgUrl, OutputStream om) {long totalBytes = 0;
String imgType= "jpeg";try{//获得connection对象
URL imgUL = newURL(imgUrl);
URLConnection imgConnection=imgUL.openConnection();
imgConnection.setReadTimeout(50000);
imgConnection.setConnectTimeout(25000);
HttpURLConnection imgUC=(HttpURLConnection) imgConnection;//设置HTTP协议的消息头
logger.debug("set header");
imgUC.setRequestMethod("GET");
imgUC.setRequestProperty("Connection", "Keep-Alive");
imgUC.setRequestProperty("Cache-Control", "no-cache");//imgUC.setRequestProperty("Content-Type", ext.toLowerCase());//
//"jpeg");// imgUC.setRequestProperty("COOKIE", "GostLiu程序员老刘");
imgUC.setDoOutput(true);
imgUC.setDoInput(true);
InputStream in=imgUC.getInputStream();byte[] buf = new byte[8192];boolean GotType = false;while (true) {int len =in.read(buf);if (len <= 0)break;if (!GotType) {
imgType= this.getImageType(buf);
GotType= true;
}
totalBytes+=len;
om.write(buf,0, len);
}
in.close();
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();return "";
}if (totalBytes > 0)returnimgType;else
return "";
}/*** 将图片文件上传到zimg服务器
*
*@paramurl
*@paramfileName
*@paramext
*@return
*/
protectedString Send(String url, String fileName, String ext) {if (ext.toLowerCase().compareTo("jpg") == 0)
ext= "jpeg";
String respXML= "";try{//获得connection对象
logger.debug("zimg server url:" +url);
URL ul= newURL(url);
URLConnection connection=ul.openConnection();
connection.setReadTimeout(50000);
connection.setConnectTimeout(25000);
HttpURLConnection uc=(HttpURLConnection) connection;//设置HTTP协议的消息头
logger.debug("zimg set header");
uc.setRequestMethod("POST");
uc.setRequestProperty("Connection", "Keep-Alive");
uc.setRequestProperty("Cache-Control", "no-cache");
uc.setRequestProperty("Content-Type", ext.toLowerCase());//"jpeg");// uc.setRequestProperty("COOKIE", "william");
uc.setDoOutput(true);
uc.setDoInput(true);
logger.debug("zimg connect server.");//与建立服务器连接
uc.connect();//设置传输模式为二进制
logger.debug("zimg upload image in binary.");
OutputStream om=uc.getOutputStream();//循环读取图片,发送到zimg服务器
FileInputStream in = newFileInputStream(fileName);byte[] buf = new byte[8192];while (true) {int len =in.read(buf);if (len <= 0)break;
om.write(buf,0, len);
}//到开输入(返回信息)流
InputStreamReader im = newInputStreamReader(uc.getInputStream(),"UTF-8");//循环读取,知道结束,获取返回信息
logger.debug("zimg get response text.");char[] bb = new char[8192];while (true) {int length =im.read(bb);if (length == -1)break;char[] bc = new char[length];for (int i = 0; i < length; i++)
bc[i]=bb[i];
respXML+= newString(bc);
}
logger.debug("zimg response:" +respXML);//关闭上下行
im.close();
uc.disconnect();
}catch(Exception e) {
logger.debug("zimg exception :" +e.getMessage());
e.printStackTrace();
}returnrespXML;
}/********** zimg 服务器返回消息定义 ***********************************/
public classZimgError {private intcode;privateString message;public intgetCode() {returncode;
}public void setCode(intcode) {this.code =code;
}publicString getMessage() {returnmessage;
}public voidsetMessage(String message) {this.message =message;
}
}public classZimgInfo {privateString md5;publicString getMd5() {returnmd5;
}public voidsetMd5(String md5) {this.md5 =md5;
}private intsize;public intgetSize() {returnsize;
}public void setSize(intsize) {this.size =size;
}
}public classZimgResult {private booleanret;privateZimgInfo info;privateZimgError error;publicZimgError getError() {returnerror;
}public voidsetError(ZimgError error) {this.error =error;
}publicString getImageUrl() {if (this.isRet()) {return ZimgClient.zimgShareUrl + this.info.getMd5();
}return "";
}public booleanisRet() {returnret;
}public void setRet(booleanret) {this.ret =ret;
}publicZimgInfo getInfo() {returninfo;
}public voidsetInfo(ZimgInfo info) {this.info =info;
}
}
}