進入編輯頁面,圖片回顯,圖片下載

需求簡介:作編輯功能的時候,進入頁面,要回顯之前上傳過的圖片javascript

解決思路:點擊編輯,後臺查詢須要編輯的信息(包含圖片信息,其實就是圖片的名字 xxx.jpg),而後把信息放到edit頁面,進入編輯頁面的時候,獲取到該信息的圖片名稱,拼裝下載路徑,而後把該路徑給img標籤的src,頁面加載src路徑的圖片時,就會進入到後臺的下載方法,把圖片從服務器上下載到本地,執行完後顯示該圖片。該方式是經過response那兩行代碼顯示的,深刻的不太懂,上代碼java

代碼:服務器

//js代碼 獲取後臺穿過倆的plan對象,而後取得plan的圖片名字plan.
<script type="text/javascript">
var plan = [[${plan}]];
if (CommnUtil.notNull(plan)) {
var planIcon = plan.planIcon;
if (CommnUtil.notNull(planIcon)) {
var imgPlanIcon = rootPath + 'serv/plan/downLoadImage?planIcon=' + planIcon;
     //給src賦值,使得當圖片加載的時候進入後臺的下載方法,執行完獲得完整的圖片路徑,再顯示圖片
$('#imgPlanIcon').attr('src', imgPlanIcon);
}
</script>
//後臺java代碼
@RequestMapping("downLoadImage")
public void downLoadFile(String planIcon, HttpServletResponse response) {
if (Tools.isEmpty(planIcon)) {
return;
}
File file = null;
file = new File(imagePath + File.separator + planIcon);
if (!file.exists()) {
file = new File(imageTempPath + File.separator + planIcon);
}

if (file.exists()) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(response.getOutputStream());
// 設置response內容的類型 https://blog.csdn.net/saytime/article/details/51497529第二種方法
response.setContentType(new MimetypesFileTypeMap().getContentType(file));
// 設置頭部信息 Content-disposition指定的類型必須是文件的擴展名
response.setHeader("Content-disposition", "attachment;filename=" + planIcon);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

總結:其實流這一起挺薄弱的,一點一點的積累吧,另外,response我本身用到的真的很少,就是設置個編碼集,或者獲取write對象,也得總結總結app

相關文章
相關標籤/搜索