1. 程式人生 > >使用JAVA線上下載圖片至本地,並上傳至FTP

使用JAVA線上下載圖片至本地,並上傳至FTP

1.首先我們需要將圖片下載至本地。相關操作類如下所示:

/**
	 * 下載檔案到本地
	 * 
	 * @param urlString
	 *            被下載的檔案地址
	 * @param filename
	 *            本地檔名
	 * @throws Exception
	 *             各種異常
	 */
	public static void download(String urlString, String filename) throws Exception {
		// 構造URL
		URL url = new URL(urlString);
	
		// 開啟連線
		URLConnection con = url.openConnection();
	
		// 輸入流
		InputStream is = con.getInputStream();

		// 1K的資料緩衝
		byte[] bs = new byte[1024];
		
		// 讀取到的資料長度
		int len;
		
		// 輸出的檔案流
		OutputStream os = new FileOutputStream(filename);
	
		// 開始讀取
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		
		// 完畢,關閉所有連結
		os.close();
		is.close();
	}

2.下載到本地以後,我們再將其上傳至FTP,FTP相關操作類如下所示:

2.1 FTP登陸類,如下:

	/**
	 * 獲取FTPClient物件
	 * @param ftpHost FTP主機伺服器
	 * @param ftpPassword FTP 登入密碼
	 * @param ftpUserName FTP登入使用者名稱
	 * @param ftpPort FTP埠 預設為21
	 * @return
	 */
	public static FTPClient getFTPClient(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort) {
		FTPClient ftpClient = null;
		try {
			ftpClient = new FTPClient();
			ftpClient.connect(ftpHost, ftpPort);// 連線FTP伺服器
			ftpClient.login(ftpUserName, ftpPassword);// 登陸FTP伺服器
			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				logger.info("未連線到FTP,使用者名稱或密碼錯誤。");
				ftpClient.disconnect();
			} else {
				logger.info("FTP連線成功。");
			}
		} catch (SocketException e) {
			e.printStackTrace();
			logger.info("FTP的IP地址可能錯誤,請正確配置。");
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("FTP的埠錯誤,請正確配置。");
		}catch(Exception evt){
			evt.printStackTrace();
		}
		return ftpClient;
	}

2.2  上傳FTP類,如下所示:
public boolean upMyFile(String fileName, InputStream ins, String Dir) {
		FTPClient ftpClient = FTPUtil.getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);

		try {

			// ftpClient.setControlEncoding("GBK");
			// // 設定編碼為中文否則檔案測試錯誤
			//
			// try {
			// ftpClient.connect(ip, prot);
			// if (!ftpClient.login(userId, pwd)) {
			// System.out.println("系統登入不成功!");
			// error = "ftp登入失敗";
			// }

			// DateFormat df = new SimpleDateFormat("yyyyMMdd");
			// String strDate = df.format(new Date());
			// 改變當前目錄到日期目錄下,如果存在該目錄就返回250,不存在則建立目錄

			//定位檔案的路徑
			if (ftpClient.cwd("/" + Dir) == 250) {
				ftpClient.cwd("/" + Dir);
				// 當前工作目錄指定到Dir目錄下,目錄存在返回 250.
				
			} else {
				ftpClient.makeDirectory("/" + Dir);
				// 這個方法不會改變當前工作目錄
				
				// 當前工作目錄指定到Dir目錄下
				ftpClient.cwd("/" + Dir);
				
			}

			System.out.println("當前工作目錄:" + ftpClient.printWorkingDirectory());

//	       FTPFile[] ftpFiles = null;
			String dir = "root/" + Dir;
//			int i = 1;
//			int nums = 0;
			// while (true) {// 該功能有待完善。有可能出現 0010
			// ftpFiles = ftpClient.listFiles(dir); // ftpClient.mlistDir();//
			// // 列出當前目錄下的檔案數
			//
			// nums = ftpFiles.length;
			// i++;
			// if (nums - 1 >= 10000) {
			// // 001資料夾中圖片個數達到1萬時,建立資料夾002,依次類推。
			// System.out.println("當前工作目錄:" +
			// ftpClient.printWorkingDirectory());
			//
			// ftpClient.changeToParentDirectory();
			//
			// // if (ftpClient.cwd("00" + i) == 250) {
			// // dir = "root/" + strDate + "/" + "00" + i;
			// // } else {
			// // ftpClient.makeDirectory("00" + i);
			// // ftpClient.cwd("00" + i);
			// // dir = "root/" + strDate + "/" + "00" + i;
			// // break;
			// // }
			// } else {
			// break;
			// }
			// }
			System.out.println(ftpClient.changeWorkingDirectory(dir));

			//設定FTP檔案型別
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			
			//ftpClient.storeFileStream(remote)
			
			if (ftpClient.storeFile(fileName, ins)) {
				file = dir + "/" + fileName;
			} else {
				System.out.println("指定檔案上傳失敗!此目錄下該使用者無權上傳檔案!");
				return false;
			}
			ftpClient.logout();
			return true;

		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

你可以自已申請一個FTP伺服器地址,帳號,密碼,埠進行測試。

(完,待續......)