java檔案儲存至伺服器

來源:互聯網
上載者:User

標籤:

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檔案儲存至伺服器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.