新闻管理软件的完美图片解决方案

类别:Java 点击:0 评论:0 推荐:

不知道您有没有做过新闻管理软件,不知道对图片处理是不是用着很麻烦的方法呢?

本文将介绍一种方法,让您省时省力轻松完成图片问题.

1.问题原因:

    我复制一篇新闻里面有新闻的图片,可是我想把这张图片改名上传到自己的空间上,一般的方法是将图片下载至本地,然后在例用上传组件上传至服务器,

2.解决方法:

/*
 * Created on 2003-1-17
 * CopyRight by http://www.designac.org
 */
package org.DesignAC.bean;
import java.io.*;
import java.net.*;
import org.DesignAC.util.Log.Logger;
import org.DesignAC.util.ErrorMessage;
import java.text.NumberFormat;
/**
 * @author biggie
 *
 * Class Function:远程图片上传至服务器指定目录,指定更名
 */
public class downloadPic {
 /** 日志 */
 private Logger log=Logger.getInstance("downloadPic");
 /** 错误信息bean*/
 ErrorMessage ErrorMessage=null;
 /** 远程图片地址 */
 private String picurl;
 /** 服务器相应该文件 */
 private String savepath;
 /** 无参数构造函数 */
 public downloadPic(){
 }
 /**
  * 构造函数
  * @param picurl 远程图片地址
  * @param savapath 服务器相应该文件
  */
 public downloadPic(String picurl,String savepath){
  this.picurl=picurl;
  this.savepath=savepath;
  NumberFormat nf = NumberFormat.getInstance();
  nf.setMaximumIntegerDigits(
 }
 /**
  * 远程下载至服务器
  * @return true上传成功,false上传失败
  */
 public boolean download(){
  String fileurl=this.picurl;
  String savepath=this.savepath;
  try{  
    int httpStatusCode;
    URL url =new URL(fileurl);
    URLConnection conn = url.openConnection();
    conn.connect();
    HttpURLConnection httpconn =(HttpURLConnection)conn;
    httpStatusCode =httpconn.getResponseCode();
    if(httpStatusCode!=HttpURLConnection.HTTP_OK){
     file://HttpURLConnection return an error code
     log.error("Connect to "+fileurl+" failed,return code:"+httpStatusCode);
     System.out.println("Connect to "+fileurl+" failed,return code:"+httpStatusCode);
     return false;
    }
    int filelen = conn.getContentLength();
    InputStream is = conn.getInputStream();
    byte[] tmpbuf=new byte[1024];
    File savefile =new File(savepath);
    if(!savefile.exists())
     savefile.createNewFile();
    FileOutputStream fos = new FileOutputStream(savefile);
    int readnum = 0;
    if(filelen<0)//for http://www.csdn.net/expert/topic/204/204361.shtm, conn.getContentLength() return -1.
    {
     while(readnum>-1)
     {
      readnum = is.read(tmpbuf);
      if(readnum>0)
       fos.write(tmpbuf,0,readnum);
     }
    }
    else
    {
     int readcount =0;
     while(readcount<filelen&&readnum!=-1)
     {
      readnum=is.read(tmpbuf);
      if(readnum>0)
      {
       fos.write(tmpbuf,0,readnum);
       readcount =readcount +readnum;
      }
     }
     if(readcount<filelen)
     {
      System.out.println("download error");
      log.error("download error!");
      is.close();
      fos.close();
      savefile.delete();
      return false;
     }
    }
    fos.flush();
    fos.close();
    is.close();
   }
   catch(Exception e)
   {
    e.printStackTrace();
    return false;
   }
   return true;
  }

}

本文地址:http://com.8s8s.com/it/it17713.htm