1. 程式人生 > >JavaWeb實現圖片非同步上傳,在前臺展示,並以二進位制儲存到資料庫

JavaWeb實現圖片非同步上傳,在前臺展示,並以二進位制儲存到資料庫

通過(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 +
                    '}';
        }
    }