package donghongyujava.servlet;
import java.io.File;
public class ShowImage extends HttpServlet {
/**
* Constructor of the object.
*/
public ShowImage() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// showImage(request, response);
downlodeImage(request, response);
}
public void showImage(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 讀取方式
// response.setContentType("application/zip");
response.setContentType("image/jpeg");
// 獲取圖片絕對路徑
String path = this.getServletContext().getRealPath("/");
File file = new File(path + "/images/WIN_20131027_214421.JPG");
// 創建文件輸入流
FileInputStream is = new FileInputStream(file);
// 響應輸出流
ServletOutputStream out = response.getOutputStream();
// 創建緩衝區
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
is.close();
out.flush();
out.close();
}
public void downlodeImage(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 獲取圖片絕對路徑
String path = this.getServletContext().getRealPath("/");
File file = new File(path + "/images/WIN_20131027_214421.JPG");
//設置頭信息,內容處理的方式,attachment以附件的形式打開,就是進行下載,並設置下載文件的命名
response.setHeader("Content-Disposition","attachment;filename="+file.getName());
// 創建文件輸入流
FileInputStream is = new FileInputStream(file);
// 響應輸出流
ServletOutputStream out = response.getOutputStream();
// 創建緩衝區
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
is.close();
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
Servlet實現將圖片寫入到網頁和實現圖片下載的功能
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
java中文件名必須和類名一致嗎
s1491695565
2020-07-06 22:33:15
JAVAEE(爲什麼叫企業版)和JAVASE(標準版)的區別與聯繫
静待_花开
2020-07-06 12:43:53
java jdk 1.8 API 下載chm 中文(免費求關注)
静待_花开
2020-07-06 12:43:41
得到當前時間和某個時間的差
caofeilong20941
2020-06-17 10:07:16
利用java在文檔中輸入
东北雷神托尔
2020-06-12 22:44:44
7-8 英文單詞排序 (25 分)
半零落
2020-05-30 23:49:51
7-3 jmu-ds-順序表區間元素刪除 (15 分)
半零落
2020-05-30 23:49:51
2018.4.18 Java異常類練習
Edison_Xian
2020-03-01 01:42:04
根據數字得到大寫的文字
caofeilong20941
2020-02-25 04:14:44
如何在Chrome下使用Postman進行rest請求測試
greenjolly
2020-02-23 15:25:59
編碼GBK不可映射漢字字符的解決方法
greenjolly
2020-02-23 15:25:59
JAVA編譯命令的區別:java和javac、javap使用詳解(java編譯命令)
greenjolly
2020-02-23 15:25:59
java編寫的網頁版 純色背景圖片去除底色工具,變成透明背景的圖片工具發佈...
webrpg
2020-02-22 20:06:15
java接口中變量
Kyrie_Wangyz
2020-02-22 18:10:31
24小時熱門文章