com.xxx.ImageServlet
ImageServlet
/images/*
“`
3.編寫(xiě)ImageServlet類(lèi),通過(guò)response.getOutputStream()將圖片寫(xiě)入response輸出流。
“`
File imageFile = new File(imagePath);
FileInputStream fileInputStream = new FileInputStream(imageFile);
BufferedInputStream buffInputStream = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[buffInputStream.available()];
buffInputStream.read(buffer);
buffInputStream.close();
response.getOutputStream().write(buffer);
response.getOutputStream().flush();
response.getOutputStream().close();
“`
以上步驟完成后,就可以將圖片上傳到服務(wù)器中了。
二、前臺(tái)代碼引入圖片
在前臺(tái)引入圖片的方式:
“`
“`
其中,“${pageContext.request.contextPath}”代表了當(dāng)前應(yīng)用在服務(wù)器上的根路徑。如上面的tomcat配置,圖片放在“images”文件夾中,即可通過(guò)“/images/圖片名”訪問(wèn)到圖片。
三、圖片的封裝
在實(shí)際開(kāi)發(fā)中,我們往往會(huì)將圖片封裝成一個(gè)類(lèi),通過(guò)類(lèi)的方法進(jìn)行加載。
“`
public class ImageUtil {
/**
* 獲得圖片流
*
* @param imagePath 圖片路徑
* @return InputStream
*/
public static InputStream getInputStream(String imagePath) {
File imageFile = new File(imagePath);
if (!imageFile.exists()) {
return null;
}
try {
return new FileInputStream(imageFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* 獲得圖片展示的url
*
* @param imageName
* @return
*/
public static String getImageUrl(String imageName) {
String urlPath = \”/images/\”;
String realPath = ImageUtil.class.getResource(\”/\”).getPath() urlPath imageName;
return realPath.replaceAll(\”\\\\\\\\\”, \”/\”);
}
}
“`
四、圖片的緩存
我們加載圖片時(shí),往往會(huì)將圖片緩存到本地。圖片的緩存有利于網(wǎng)絡(luò)傳輸、加快頁(yè)面加載速度。
下面是一個(gè)簡(jiǎn)單的圖片緩存代碼:
“`
private static ConcurrentHashMap<String, SoftReference> cache = new ConcurrentHashMap<String, SoftReference>();
public static BufferedImage getImage(String imageName) {
SoftReference reference = cache.get(imageName);
BufferedImage image = null;
if (reference != null) {
image = reference.get();
}
if (image == null) {
image = loadImage(ImageUtil.getImageUrl(imageName));
if (image != null) {
cache.put(imageName, new SoftReference(image));
}
}
return image;
}
“`
以上就是SSM云服務(wù)器如何訪問(wèn)圖片的方法,同時(shí)也讓我們更深一步地了解了Java Web開(kāi)發(fā)的一些基礎(chǔ)知識(shí)。
以上就是小編關(guān)于“ssm云服務(wù)器怎么訪問(wèn)圖片”的分享和介紹
西部數(shù)碼(west.cn)是經(jīng)工信部審批,持有ISP、云牌照、IDC、CDN全業(yè)務(wù)資質(zhì)的正規(guī)老牌云服務(wù)商,自成立至今20余年專(zhuān)注于域名注冊(cè)、虛擬主機(jī)、云服務(wù)器、企業(yè)郵箱、企業(yè)建站等互聯(lián)網(wǎng)基礎(chǔ)服務(wù)!
公司自研的云計(jì)算平臺(tái),以便捷高效、超高性?xún)r(jià)比、超預(yù)期售后等優(yōu)勢(shì)占領(lǐng)市場(chǎng),穩(wěn)居中國(guó)接入服務(wù)商排名前三,為中國(guó)超過(guò)50萬(wàn)網(wǎng)站提供了高速、穩(wěn)定的托管服務(wù)!先后獲評(píng)中國(guó)高新技術(shù)企業(yè)、中國(guó)優(yōu)秀云計(jì)算服務(wù)商、全國(guó)十佳IDC企業(yè)、中國(guó)最受歡迎的云服務(wù)商等稱(chēng)號(hào)!
目前,西部數(shù)碼高性能云服務(wù)器正在進(jìn)行特價(jià)促銷(xiāo),最低僅需48元!
http://ps-sw.cn/cloudhost/