通过(ajaxFileupload.js)提供的ajaxFileUpload方法,异步上传图片,在后台获取并转二进制先存入session中,成功后返回图片的id到ajax,并通过jQuery改变 img src的地址请求该图片的二进制资源。
二次上传会覆盖前一次保存在session中的对象,确定保存后会把session中的对象保存到出数据库中。就可以通过id来请求数据库中的图片二进制资源。
- 代码示例spring+hibernate(前端依赖jquery.js,ajaxFileUpload.js)
- 前台HTML代码
<%-- 图片展示 src为默认图片资源--% <img id="upload" class="pointer img-rounded" alt="点击上传" src="../../../resources/img/upload.jpg" width="100%"> <%-- 图片上传 --> <input id="upfile" style="display: none" type="file" name="upfile">
- JavaScript
/** * 上传图片 */ $("#upload").on('click',function(){ $("#upfile").click(); }); $("#upfile").on("change",upfile); function upfile(){ $.ajaxFileUpload({ secureuri:false, url:"upImg.aj", dataType:"json", //fileElementId是img标签的id fileElementId:'upfile', success:function(data){ //上传成功后改变<img>标签的src地址,id参数其实不需要,主要是为了刷新img的图片资源。 $("#upload").attr("src","getCurImg.aj?id="+data.message); //重新绑定事件,防止二次上传时失效 $("#upfile").on("change",upfile); } }); }
- 后台Controller
/** * 上传图片到session * @param response * @param request */ @RequestMapping(value = "/upImg.aj", method = RequestMethod.POST) public void upImgSession(HttpServletResponse response, HttpServletRequest request, HttpSession httpSession) { //获取图片 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 根据前台name名称得到上传的文件 MultipartFile img = multipartRequest.getFile("upfile"); // 定义一个数组,用于保存可上传的文件类型 List fileTypes = new ArrayList(); fileTypes.add("jpg"); fileTypes.add("jpeg"); fileTypes.add("bmp"); fileTypes.add("png"); String fileName = img.getOriginalFilename(); Long id=null; ResultModel rm=null; if(!(fileName==null ||"".equals(fileName))){ String extensionName = fileName.substring(fileName.lastIndexOf(".")+1); if(fileTypes.contains(extensionName)){ //扩展名合法 try{ id = System.currentTimeMillis(); byte[] content=img.getBytes(); String extension="image/"+extensionName; WjbDO wjbDO = new WjbDO(content,extension,id); httpSession.setAttribute("curImg",wjbDO); }catch (IOException e){ e.printStackTrace(); } rm=new ResultModel(id.toString(), 1); } }else{ rm=new ResultModel("上传失败", 0); } ResponseBuilder rb = new ResponseBuilder(); try { rb.writeJsonResponse(response,rm); }catch (IOException e){ log.info("IOException",e); } } /** * 从session请求图片二进制流 * @param response * @param request */ @RequestMapping(value = "/getCurImg.aj", method = RequestMethod.GET) public String getCurImg(HttpServletResponse response,HttpServletRequest request,HttpSession httpSession) { WjbDO wjbDO = (WjbDO)httpSession.getAttribute("curImg"); //设置文件格式 response.setContentType(wjbDO.getExtension()); try{ OutputStream out = response.getOutputStream(); out.write(wjbDO.getContent()); out.close(); }catch (IOException e){ log.error("输出图片流失败",e); } return null; } /** * 确认保存后提交图片到数据库 * @param response */ @RequestMapping(value = "/zcdj.aj", method = RequestMethod.POST) public void zcdjSave(HttpServletResponse response, HttpServletRequest request,HttpSession httpSession) { //保存上传图片 WjbDO wjbDO = (WjbDO)httpSession.getAttribute("curImg"); if (wjbDO!=null){ zcModel.setImg(wjbDO.getId()); wjService.saveWj(wjbDO); } }
- WjService.java
public interface WjService { boolean saveWj(WjbDO wjbDO); WjbDO findById(Long id); boolean update(WjbDO wjbDO); boolean del(Long id); }
- WjServiceImpl.java
public class WjServiceImpl implements WjService { WjbDao wjbDao; @Transactional public boolean saveWj(WjbDO wjbDO){ return wjbDao.save(wjbDO); } public WjbDO findById(Long id){ return wjbDao.findById(id); } @Transactional public boolean update(WjbDO wjbDO){ wjbDao.attachDirty(wjbDO); return true; } @Transactional public boolean del(Long id){ WjbDO wjbDO = wjbDao.findById(id); if (wjbDO!=null){ wjbDao.delete(wjbDO); return true; } return false; } public WjbDao getWjbDao() { return wjbDao; } public void setWjbDao(WjbDao wjbDao) { this.wjbDao = wjbDao; } }
- WjbDao.java
public class WjbDao extends HibernateDaoSupport{ private static final Logger log = LoggerFactory.getLogger(WjbDao.class); protected void initDao(){ // do nothing } public boolean save(WjbDO transientInstance){ log.debug("saving WjbDO instance"); try{ Serializable serializable = getHibernateTemplate().save(transientInstance); if (serializable != null){ log.debug("save successful"); return true; } }catch(RuntimeException re){ log.error("save failed",re); throw re; } return false; } public void delete(WjbDO persistentInstance) { log.debug("deleting WjbDO instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } // 刷新Session // getSession().flush(); } public WjbDO findById(Long id) { log.debug("getting WjbDO instance with id: " + id); try { WjbDO instance = (WjbDO) getHibernateTemplate().get( "nju.software.fams.data.daoobject.WjbDO", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public void attachDirty(WjbDO instance) { log.debug("attaching dirty WjbDO instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(WjbDO instance) { log.debug("attaching clean WjbDO instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void delById(long id){ log.debug("attaching clean ZcDO instance"); Session session = getSessionFactory().getCurrentSession(); session.createQuery("delete from WjbDO where id=?").setParameter(0,id).executeUpdate(); } }
- WjbDO.java
@Entity @Table(name = "FAMS_WJB",schema = "FixAssetMS") public class WjbDO { private Long id; private byte[] content; /** * 扩展名 */ private String extension; public WjbDO(byte[] content, String extension, Long id) { this.content = content; this.extension = extension; this.id = id; } public WjbDO() { } @Id @Column(name = "ID_WJ") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "CONTENT") public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } @Column(name = "EXTENSION") public String getExtension() { return extension; } public void setExtension(String extension) { this.extension = extension; } @Override public String toString() { return "WjbDO{" + "extension='" + extension + '\'' + ", id=" + id + '}'; } }