天天看點

Java下載下傳圖檔伺服器上的資源

工具類代碼如下:

package util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;

/**
 * 下載下傳http對應URL的圖檔資源
 *
 */
public class DownloadImage{
	/**
     * 日志
     */
    protected  final Logger logger = Logger.getLogger(DownloadImage.class);
	
	private String ImageRootPath = "/data/application/tempImg";
	
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		DownloadImage downloadImage = new DownloadImage();
		String httpUrlStr = "https://avatar.csdn.net/3/6/0/1_qq_25646191.jpg?1523447843";
		String fileName  = System.currentTimeMillis() + ".png";
		downloadImage.download(httpUrlStr, fileName);
	}
	
	/**
	 * 下載下傳圖檔
	 * @param httpUrlStr
	 * @param subFolderName
	 * @param filename
	 * @return
	 */
	public String download(String httpUrlStr, String filename) {
		return download(httpUrlStr,filename,ImageRootPath);
	}
	
	@SuppressWarnings("finally")
	private String download(String httpUrlStr, String filename,String savePath){
		InputStream is = null;
		OutputStream os = null;
		String filePath = null;
		try {
			filePath = savePath + File.separator + filename;
			logger.info(String.format("下載下傳圖檔... url = {%s}, filePath = {%s} ", httpUrlStr, filePath));
		    // 構造URL
		    URL url = new URL(httpUrlStr);
		    // 打開連接配接
		    URLConnection con = url.openConnection();
		    //設定請求逾時為5s
		    con.setConnectTimeout(5*1000);
		    // 輸入流
		    is = con.getInputStream();
		
		    // 1K的資料緩沖
		    byte[] bs = new byte[1024];
		    // 讀取到的資料長度
		    int len;
		    // 輸出的檔案流
		   File sf=new File(savePath);
		   if(!sf.exists()){
			   sf.mkdirs();
		   }
		   os = new FileOutputStream(filePath);
		    // 開始讀取
		    while ((len = is.read(bs)) != -1) {
		      os.write(bs, 0, len);
		    }
		    logger.info(String.format("下載下傳圖檔成功 圖檔存放路徑 = {%s}", filePath));
		} catch (MalformedURLException e) {
			logger.error("下載下傳圖檔失敗 : " + e.getMessage());
			e.printStackTrace();
		} catch (Exception e){
			logger.error("普通異常下載下傳圖檔失敗 : " + e.getMessage());
		} finally {
			// 完畢,關閉所有連結
			try {
				if(null != os){
					os.close();
				}
				if(null != is){
					is.close();
				}
			} catch (IOException e) {
				logger.error("下載下傳圖檔關閉流失敗: " + e.getMessage());
			}
			return filePath;
		}
	}
	
	
    /**
     * 删除臨時檔案  注意,隻能删除指定目錄下面的臨時檔案
     * @param   supplierId  商戶ID
     * @param   fileName    被删除檔案的檔案名
     * @return 單個檔案删除成功傳回true,否則傳回false
     */
    public boolean deleteFile(String fileName) {
    	boolean flag = false;
    	try{
    		String sPath = getImageRootPath() + File.separator + fileName;
    		logger.info(String.format("删除臨時檔案 path = {%s} ", sPath));
    		File file = new File(sPath);
    		// 路徑為檔案且不為空則進行删除
    		if (file.isFile() && file.exists()) {
    			file.delete();
    			flag = true;
    		}
    	} catch(Exception e){
    		logger.info("删除檔案異常 " + e.getMessage());
    	}
    	return flag;
    }
	
	public String getImageRootPath() {
		return ImageRootPath;
	}

	public void setImageRootPath(String ImageRootPath) {
		this.ImageRootPath = ImageRootPath;
	} 
}
           

運作結果如下:

Java下載下傳圖檔伺服器上的資源

下載下傳結果:

Java下載下傳圖檔伺服器上的資源