spring使用流讀取指定路徑圖片
//流讀取圖片
package cn.fenghuait.controller;
import java.io.FileInputStream;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.fenghuait.service.SysParameterService;
@Controller
@RequestMapping("/picture")
public class ShowPicController extends BaseController{
private static Log logger = LogFactory.getLog(ShowPicController.class);
@Autowired
private SysParameterService parameterService;
@RequestMapping(value="/showPic")
public @ResponseBody Map<String,Object> showPic(HttpServletRequest request,HttpServletResponse response) throws Exception{
try{
String basePath = parameterService.getProblemPic();
String str = request.getParameter("picName");
String realName = basePath+"/"+str;
FileInputStream fs = new FileInputStream(realName);
int b=fs.available(); //得到檔案大小
byte data[]=new byte[b];
fs.read(data); //讀資料
response.setContentType("image/*"); //設定返回的檔案型別
ServletOutputStream toClient=response.getOutputStream(); //得到向客戶端輸出二進位制資料的物件
toClient.write(data); //輸出資料
toClient.flush();
toClient.close();
fs.close();
}catch(Exception e){
e.printStackTrace();
logger.error(e);
}
return null;
}
}
//查詢圖片名稱
info=problemInfoService.getProblemInfoById(problemInfo.getProblemId());
List<String> list = new ArrayList<String>();
if(info.getPicturePath()!=null&&!"".equals(info.getPicturePath().trim())){
String str = info.getPicturePath();
String[] strs = str.split(",");
String pic = "";
for(int i = 0;i<strs.length;i++){
pic = strs[i];
list.add(pic);
}
}
mav.addObject("problem", info);
mav.addObject("realName", list);
//jsp顯示圖片
<c:forEach items="${realName }" var="item">
<li><a target="_blank"><img src="${basePath}/picture/showPic?picName=${item}" alt="民情圖片" /></a></li></c:forEach>