標籤:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageRequest{
/**
* 讀取網狀圖片並儲存至伺服器硬碟中
* @param imgUrl
* @return 圖片儲存的伺服器路徑
*/
public static String getImages(String imgUrl){
String imgPath = "";
try{
//new一個URL對象
URL url = new URL(imgUrl);
//開啟連結
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//佈建要求方式為"GET"
conn.setRequestMethod("GET");
//逾時回應時間為5秒
conn.setConnectTimeout(5 * 1000);
//通過輸入資料流擷取圖片資料
InputStream inStream = conn.getInputStream();
//得到圖片的位元據,以二進位封裝得到資料,具有通用性
byte[]data = readInputStream(inStream);
imgPath = ImageRequest.class.getClassLoader().getResource("").getPath();
imgPath = imgPath.split("WEB-INF")[0];
imgPath = imgPath+"images/"+"haha.jpg";
//new一個檔案對象用來儲存圖片,預設儲存當前工程根目錄
File imageFile = new File(imgPath);
//建立輸出資料流
FileOutputStream outStream = new FileOutputStream(imageFile);
//寫入資料
outStream.write(data);
//關閉輸出資料流
outStream.close();
//伺服器檔案路徑
imgPath = imgPath.split("WebRoot")[1];
System.out.println(imgPath);
}catch(Exception e){e.printStackTrace();}
return imgPath;
}
/**
* 讀取檔案流
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//建立一個Buffer字串
byte[] buffer = new byte[1024];
//每次讀取的字串長度,如果為-1,代表全部讀取完畢
int len = 0;
//使用一個輸入資料流從buffer裡把資料讀取出來
while( (len=inStream.read(buffer)) != -1 ){
//用輸出資料流往buffer裡寫入資料,中間參數代表從哪個位置開始讀,len代表讀取的長度
outStream.write(buffer, 0, len);
}
//關閉輸入資料流
inStream.close();
//把outStream裡的資料寫入記憶體
return outStream.toByteArray();
}
public static void main(String[] args) throws Exception {
ImageRequest.getImages("http://image.meilele.com/images/201311/1385338928366387259.jpg");
}
}
java檔案儲存至伺服器