com.xxx.ImageServlet
ImageServlet
/images/*
“`
3.編寫ImageServlet類,通過response.getOutputStream()將圖片寫入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ù)器中了。
二、前臺代碼引入圖片
在前臺引入圖片的方式:
“`
“`
其中,“${pageContext.request.contextPath}”代表了當(dāng)前應(yīng)用在服務(wù)器上的根路徑。如上面的tomcat配置,圖片放在“images”文件夾中,即可通過“/images/圖片名”訪問到圖片。
三、圖片的封裝
在實際開發(fā)中,我們往往會將圖片封裝成一個類,通過類的方法進行加載。
“`
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(\”\\\\\\\\\”, \”/\”);
}
}
“`
四、圖片的緩存
我們加載圖片時,往往會將圖片緩存到本地。圖片的緩存有利于網(wǎng)絡(luò)傳輸、加快頁面加載速度。
下面是一個簡單的圖片緩存代碼:
“`
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ù)器如何訪問圖片的方法,同時也讓我們更深一步地了解了Java Web開發(fā)的一些基礎(chǔ)知識。
以上就是小編關(guān)于“ssm云服務(wù)器怎么訪問圖片”的分享和介紹
三五互聯(lián)(35.com)是經(jīng)工信部審批,持有ISP、云牌照、IDC、CDN全業(yè)務(wù)資質(zhì)的正規(guī)老牌云服務(wù)商,自成立至今20余年專注于域名注冊、虛擬主機、云服務(wù)器、企業(yè)郵箱、企業(yè)建站等互聯(lián)網(wǎng)基礎(chǔ)服務(wù)!
公司自研的云計算平臺,以便捷高效、超高性價比、超預(yù)期售后等優(yōu)勢占領(lǐng)市場,穩(wěn)居中國接入服務(wù)商排名前三,為中國超過50萬網(wǎng)站提供了高速、穩(wěn)定的托管服務(wù)!先后獲評中國高新技術(shù)企業(yè)、中國優(yōu)秀云計算服務(wù)商、全國十佳IDC企業(yè)、中國最受歡迎的云服務(wù)商等稱號!
目前,三五互聯(lián)高性能云服務(wù)器正在進行特價促銷,最低僅需48元!
http://www.shinetop.cn/cloudhost/