当前位置: 代码迷 >> J2EE >> 求用JSP编写把图片存到数据库,再把图片从数据库读取的程序。解决方案
  详细解决方案

求用JSP编写把图片存到数据库,再把图片从数据库读取的程序。解决方案

热度:183   发布时间:2016-04-22 02:32:26.0
求用JSP编写把图片存到数据库,再把图片从数据库读取的程序。
就像QQ空间里面,更改头像一样...怎么去实现?求解答啊

------解决方案--------------------
保存方法
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(10*1024*1024);
fu.setSizeThreshold(4096);
byte[] bContent = null;
List fileItems = fu.parseRequest(request);
 
Iterator i = fileItems.iterator();
if(i.hasNext()) {
FileItem fi = (FileItem)i.next();
fileName = fi.getName();
bContent = fi.get();
}

cmsFileAttachment = new CmsFileAttachment();
cmsFileAttachment.setContent(bContent);
cmsFileAttachmentService.addAttachment(cmsFileAttachment);


查看servlet

public class ImageServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-control", "no-cache");
response.setDateHeader("Expires", 0);
try{
String aFolderId = request.getParameter("folderId");
String aSeqNo = request.getParameter("seqNo");

aFileAttachment=加载对象方法

byte[] imageData = (byte[]) aFileAttachment.getContent();

InputStream in = new ByteArrayInputStream(imageData);
ServletOutputStream sos = response.getOutputStream();
int len = 0;
byte[] b = new byte[1024];
response.reset();
response.setContentType("image/gif");
while((len = in.read(b)) > 0)
sos.write(b,0,len);

sos.close();
in.close();
}catch (Exception e){
e.printStackTrace();
}
}
  相关解决方案