Java 快讯功能开发记录

2024-05-12 13:48
文章标签 java 功能 开发 记录 快讯

本文主要是介绍Java 快讯功能开发记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


Hibernate实体类

package com.wamei.entity;import org.apache.commons.lang.time.DateFormatUtils;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;/*** 快讯类型* @author qixuan.chen**/
@Entity
@Table(name = "T_NEWS_FLASH")
public class NewsFlash implements Serializable {/*** */private static final long serialVersionUID = 1L;private String id;	//主键IDprivate NewsFlashType newsFlashType;private String content;	// 快讯内容private String images;	//图片//数组private String videoCover;	//视频封面//数组private String videos;	//视频//数组private String linkType; // (1文章ID 2H5链接)private String link; // ID/全文链接private int status;	//状态(0下线 1上线)@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )private Date publishTime;//定时发布时间@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )private Date createTime;//发布时间@Id@GeneratedValue(generator = "paymentableGenerator")    @GenericGenerator(name = "paymentableGenerator", strategy = "uuid")   @Column(name = "ID")public String getId() {return id;}public void setId(String id) {this.id = id;}@ManyToOne@JoinColumn(name = "NewsFlashType_ID")public NewsFlashType getNewsFlashType() {return newsFlashType;}public void setNewsFlashType(NewsFlashType newsFlashType) {this.newsFlashType = newsFlashType;}@Column(name = "CONTENT",length=500)public String getContent() {return content;}public void setContent(String content) {this.content = content;}@Column(name = "IMAGES",columnDefinition="TEXT")public String getImages() {return images;}public void setImages(String images) {this.images = images;}@Column(name = "VIDEOS",columnDefinition="TEXT")public String getVideos() {return videos;}public void setVideos(String videos) {this.videos = videos;}@Column(name = "LINK_TYPE")public String getLinkType() {return linkType;}public void setLinkType(String linkType) {this.linkType = linkType;}@Column(name = "VIDEO_COVER",columnDefinition="TEXT")public String getVideoCover() {return videoCover;}public void setVideoCover(String videoCover) {this.videoCover = videoCover;}@Column(name = "LINK")public String getLink() {return link;}public void setLink(String link) {this.link = link;}@Column(name = "STATUS", columnDefinition = "bigint default 1")public int getStatus() {return status;}public void setStatus(int status) {this.status = status;}@Column(name = "PUBLISH_TIME")public Date getPublishTime() {return publishTime;}public void setPublishTime(Date publishTime) {this.publishTime = publishTime;}@Column(name = "CREATE_TIME")public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}@Transientpublic String getPublishTimeStr(){String str = "";try{str = DateFormatUtils.format(this.publishTime, "yyyy-MM-dd HH:mm:ss");}catch(Exception e){}return str;}@Transientpublic String getCreateTimeStr(){String str = "";try{str = DateFormatUtils.format(this.createTime, "yyyy-MM-dd HH:mm:ss");}catch(Exception e){}return str;}}

快讯类型实体类:

package com.wamei.entity;import org.apache.commons.lang.time.DateFormatUtils;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;/*** 快讯类型* @author qixuan.chen**/
@Entity
@Table(name = "T_NEWS_FLASH_TYPE")
public class NewsFlashType implements Serializable {/*** */private static final long serialVersionUID = 1L;private String id;	//主键IDprivate String name;	//名称private String icon;	//图标private int orderIndex;	//排序编号private int status;	//状态(0下线 1上线)@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )private Date createTime;private Set<NewsFlash> newsFlash;@Id@GeneratedValue(generator = "paymentableGenerator")    @GenericGenerator(name = "paymentableGenerator", strategy = "uuid")   @Column(name = "ID")public String getId() {return id;}public void setId(String id) {this.id = id;}@Column(name = "NAME")public String getName() {return name;}public void setName(String name) {this.name = name;}@Column(name = "ICON")public String getIcon() {return icon;}public void setIcon(String icon) {this.icon = icon;}@Column(name = "ORDER_INDEX")public int getOrderIndex() {return orderIndex;}public void setOrderIndex(int orderIndex) {this.orderIndex = orderIndex;}@Column(name = "STATUS", columnDefinition = "bigint default 1")public int getStatus() {return status;}public void setStatus(int status) {this.status = status;}@Column(name = "CREATE_TIME")public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}@OneToMany(mappedBy="newsFlashType",fetch=FetchType.EAGER,cascade=CascadeType.REMOVE)@OrderBy(value = "publishTime DESC")public Set<NewsFlash> getNewsFlash() {return newsFlash;}public void setNewsFlash(Set<NewsFlash> newsFlash) {this.newsFlash = newsFlash;}@Transientpublic String getCreateTimeStr(){String str = "";try{str = DateFormatUtils.format(this.createTime, "yyyy-MM-dd HH:mm:ss");}catch(Exception e){}return str;}}


控制层逻辑:

package com.wamei.controller;import com.wamei.entity.NewsFlash;
import com.wamei.entity.NewsFlashType;
import com.wamei.entity.PaginQueryResult;
import com.wamei.service.BaseService;
import com.wamei.tool.VideoConvertUtil;
import com.wamei.util.FileHelper;
import com.wamei.util.JsonResponseHelper;
import com.wamei.util.SystemConstants;
import com.wamei.util.VideoPreviewImageUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;/*** 快讯管理 Controller.** @author qixuan.chen* @version 1.0*/
@Controller
@RequestMapping({"/newsFlashController"})
public class NewsFlashController {private final static Logger logger = Logger.getLogger(NewsFlashController.class);@Resource(name = "newsFlashManager")private BaseService<NewsFlash> newsFlashSrv;@Resource(name = "newsFlashTypeManager")private BaseService<NewsFlashType> newsFlashTypeSrv;/*** 查询列表* @param request* @param response*/@RequestMapping(value = "query", method = {RequestMethod.POST, RequestMethod.GET})@ResponseBodypublic void query(HttpServletRequest request, HttpServletResponse response) {StringBuffer sb = new StringBuffer(""); // 返回结果try {int page = Integer.valueOf(request.getParameter("page"));int pageSize = Integer.valueOf(request.getParameter("pageSize"));PaginQueryResult<NewsFlash> pqr = new PaginQueryResult<>();String hql = " from NewsFlash t where 1=1 ";List<Object> paramValues = new ArrayList<Object>();String startTime = request.getParameter("startFactTime");String endTime = request.getParameter("endFactTime");if(StringUtils.isNotEmpty(startTime)){hql+="and t.publishTime >= ? ";Date startDate;try {startDate = DateUtils.parseDate(startTime+" 00:00:00", "yyyy-MM-dd HH:mm:ss");} catch (ParseException e) {startDate = new Date();}paramValues.add(startDate);}if(StringUtils.isNotEmpty(endTime)){hql+="and t.publishTime <= ? ";Date endDate;try {endDate = DateUtils.parseDate(endTime+" 23:59:59", "yyyy-MM-dd HH:mm:ss");} catch (ParseException e) {endDate = new Date();}paramValues.add(endDate);}hql += "Order By t.createTime DESC";List<NewsFlash> list = newsFlashSrv.list(hql, paramValues.toArray(), page, pageSize);//存放结果集pqr.setData(list);pqr.setTotal(newsFlashSrv.getQueryResultRecordCount(hql, paramValues.toArray(), 1, Integer.MAX_VALUE, false, null));// 分页查询数据sb.append("{\"statusCode\":\"1\", \"msg\":\"\", \"errorCode\":\"\", \"result\":{\"totalRecords\":" + pqr.getTotal() + ",\"totalPage\":" + pqr.getTotalPage(pageSize) + ",\"data\":" + JsonResponseHelper.toJson(pqr.getData()) + "}}");} catch (Exception e) {e.printStackTrace();sb.append("{\"statusCode\":\"0\", \"msg\":\"获取数据失败\", errorCode:\"\", result:{}}");}JsonResponseHelper.renderText(sb.toString(), response);}/*** 删除* @param moId* @param response*/@RequestMapping(value = "/delete/{moId}")@ResponseBodypublic void delete(@PathVariable String moId, HttpServletResponse response) {StringBuffer sb = new StringBuffer();try {newsFlashSrv.delete(moId);sb.append("{\"statusCode\":\"1\", \"msg\":\"\", \"errorCode\":\"\", \"result\":{}}");} catch (Exception e) {e.printStackTrace();sb.append("{\"statusCode\":\"0\", \"msg\":\"删除数据失败\", \"errorCode\":\"\", \"result\":{}}");}JsonResponseHelper.renderText(sb.toString(), response);}/*** 保存信息* @param mo* @param request* @param response*/@RequestMapping(value = "save", method = RequestMethod.POST)@ResponseBodypublic void save(@ModelAttribute("form") NewsFlash mo, HttpServletRequest request, HttpServletResponse response) {String publishTime = ServletRequestUtils.getStringParameter(request, "publishTime", "");Integer newsFlashStatus = ServletRequestUtils.getIntParameter(request, "newsFlashStatus", 0);String[] imageArray = ServletRequestUtils.getStringParameters(request, "imageUrl");String[] videos = ServletRequestUtils.getStringParameters(request, "videos");String newsFlashTypeId = ServletRequestUtils.getStringParameter(request, "newsFlashType.id","");StringBuffer sb = new StringBuffer();// 保存图片String images = "";if(null!=imageArray && imageArray.length>0){if(imageArray.length<=10){for(int i=0;i<imageArray.length;i++){images += imageArray[i]+",";}mo.setImages(images.substring(0,images.length()-1));}}else{mo.setImages("");}//保存视频地址\封面String videoCoover = "",videoLink = "";if(null!=videos && videos.length>0){if(videos.length<=5){for(int i=0;i<videos.length;i++){String[] array = videos[i].split("@");videoCoover += array[0]+",";videoLink += array[1]+",";}}mo.setVideoCover(videoCoover.substring(0,videoCoover.length()-1));mo.setVideos(videoLink.substring(0,videoLink.length()-1));}else{mo.setVideoCover("");mo.setVideos("");}if(StringUtils.isNotEmpty(mo.getContent())){String content = mo.getContent();content = content.replace("'","");content = content.replace("\"","");content = content.replaceAll("\\\\","");content = content.replaceAll("\r\n", "<br>");
//            content = content.replaceAll("\r", "\\\\r");
//            content = content.replaceAll("\n", "\\\\n");mo.setContent(content);}try {if(StringUtils.isNotEmpty(newsFlashTypeId)){NewsFlashType type = new NewsFlashType();type.setId(newsFlashTypeId);mo.setNewsFlashType(type);}else{mo.setNewsFlashType(null);}if (null != mo && StringUtils.isNotEmpty(mo.getId())) {mo.setStatus(newsFlashStatus);newsFlashSrv.update(mo);} else {mo.setStatus(1);//下线0 上线1,默认为上线状态if(StringUtils.isNotEmpty(publishTime)){SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date time = sdf.parse(publishTime);mo.setPublishTime(time);}else{mo.setPublishTime(new Date());}mo.setCreateTime(new Date());newsFlashSrv.create(mo);}sb.append("{\"statusCode\":\"1\", \"msg\":\"\", \"errorCode\":\"\", \"result\":{}}");} catch (Exception e) {e.printStackTrace();sb.append("{\"statusCode\":\"0\", \"msg\":\"保存数据失败!\", \"errorCode\":\"\", \"result\":{}}");}JsonResponseHelper.renderText(sb.toString(), response);}/*** 上传图片* @param response*/@RequestMapping(value = "/upload/image",method = RequestMethod.POST)@ResponseBodypublic void saveUploadImage(HttpServletRequest request,HttpServletResponse response) {StringBuffer sb = new StringBuffer();String savePath="upload/image/";String picType="png";String originalFile ="";Integer width=290;Integer height=182;String picSrc = "";try {MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;MultipartFile file = multipartRequest.getFile("file");if (file != null) {originalFile=file.getOriginalFilename();picType = originalFile.substring(originalFile.lastIndexOf(".")+1,originalFile.length());//picType = StringUtils.isNotEmpty(picType)?picType:"png";logger.info("图片格式:"+picType);String fileName = UUID.randomUUID().toString().replace("-", "")+"."+picType;String path = request.getSession().getServletContext().getRealPath(savePath+fileName);picSrc = "http://"+JsonResponseHelper.serverAddress+"/wamei/"+savePath+fileName;//BufferedImage newImage = ImageUtil.getNewImage(file,width,height);if (file.getSize() > 0) {File destFile = new File(path);if("gif".equalsIgnoreCase(picType)){FileHelper.saveGifImageInputStream(file.getInputStream(), path);}else{//ImageIO.write(newImage, picType, destFile);FileHelper.saveFile(file.getBytes(), path);}}if(StringUtils.isNotEmpty(originalFile) && !originalFile.equals(SystemConstants.USER_DEFAULT_AVATAR)){FileHelper.deleteWameiFile(request, originalFile);}}sb.append("{\"statusCode\":\"1\", \"msg\":\"上传成功!\", \"errorCode\":\"\", \"result\":\""+picSrc+"\"}");} catch (Exception e) {e.printStackTrace();sb.append("{\"statusCode\":\"0\", \"msg\":\"上传失败\", \"errorCode\":\"\", \"result\":{}}");}JsonResponseHelper.renderText(sb.toString(), response);}/*** 上传视频* @param response*/@RequestMapping(value = "/upload/video",method = RequestMethod.POST)@ResponseBodypublic void saveUploadVideo(HttpServletRequest request,HttpServletResponse response) {StringBuffer sb = new StringBuffer();String savePath="upload/video/";String videoName = "",videoType="mp4";String picSrc = "",videoLink = "";//视频封面//视频链接boolean mark = false,status = false;try {MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;MultipartFile file = multipartRequest.getFile("videoFile");if (file != null) {videoName=file.getOriginalFilename();videoType = videoName.substring(videoName.lastIndexOf(".")+1);// 截取视频文件格式videoType = StringUtils.isNotEmpty(videoType)?videoType:"mp4";String fileName = UUID.randomUUID().toString().replace("-", "")+"."+videoType;String path = request.getSession().getServletContext().getRealPath(savePath+fileName);videoLink = "http://"+JsonResponseHelper.serverAddress+"/wamei/"+savePath+fileName;videoLink = videoLink.substring(0,videoLink.lastIndexOf("."))+".mp4";//视频文件大小限制在30Mif (file.getSize() > 0 && file.getSize() <= 31457280) {logger.info("file size:=================== "+file.getSize());mark = FileHelper.saveUploadedVideo(request,videoName, file, path);if(mark){picSrc = VideoPreviewImageUtil.processImg(path);//截取视频封面if(null!=picSrc){status = true;}//视频格式转换VideoConvertUtil v1= new VideoConvertUtil(path,fileName);Thread t1 = new Thread(v1);t1.start();}}}if(status){sb.append("{\"statusCode\":\"1\", \"msg\":\"上传成功!\", \"errorCode\":\"\",\"videoLink\":\""+videoLink+"\", \"videoConver\":\""+picSrc+"\"}");}else{sb.append("{\"statusCode\":\"0\", \"msg\":\"上传失败\", \"errorCode\":\"\", \"result\":{}}");}} catch (Exception e) {e.printStackTrace();sb.append("{\"statusCode\":\"0\", \"msg\":\"上传失败\", \"errorCode\":\"\", \"result\":{}}");}JsonResponseHelper.renderText(sb.toString(), response);}/*** 获取数据* @param moId* @return* @throws Exception*/@RequestMapping(value = "/edit/{moId}")@ResponseBodypublic ModelAndView edit(@PathVariable String moId) throws Exception {ModelAndView modelAndView = new ModelAndView("pages/articles/newsflash_edit");List<NewsFlashType>  list = newsFlashTypeSrv.list();if(list.size()>0){modelAndView.addObject("typeList", list);}if (StringUtils.isNotEmpty(moId)) {NewsFlash mo = newsFlashSrv.find(moId);modelAndView.addObject("mo", mo);}return modelAndView;}/*** 上线、下线* @param moId* @param response*/@RequestMapping(value = "/updateStatus/{moId}")@ResponseBodypublic void updateStatus(@PathVariable String moId, HttpServletRequest request,HttpServletResponse response) {Integer status = ServletRequestUtils.getIntParameter(request, "status", 0);StringBuffer sb = new StringBuffer();try {NewsFlash obj = newsFlashSrv.find(moId);if(null != obj){obj.setStatus(status);newsFlashSrv.update(obj);}sb.append("{\"statusCode\":\"1\", \"msg\":\"\", \"errorCode\":\"\", \"result\":{}}");} catch (Exception e) {e.printStackTrace();sb.append("{\"statusCode\":\"0\", \"msg\":\"删除数据失败\", \"errorCode\":\"\", \"result\":{}}");}JsonResponseHelper.renderText(sb.toString(), response);}
}



编辑页面:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
<title>挖媒管理后台 - 快讯添加/编辑</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /><!-- bootstrap -->
<link href="/wamei/pages/css/bootstrap/bootstrap.css" rel="stylesheet" />
<link href="/wamei/pages/css/bootstrap/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<link href="/wamei/pages/css/bootstrap/bootstrap-responsive.css" rel="stylesheet" />
<link href="/wamei/pages/css/bootstrap/bootstrap-overrides.css" type="text/css"rel="stylesheet" /><!-- global styles -->
<link rel="stylesheet" type="text/css" href="/wamei/pages/css/elements.css" />
<link rel="stylesheet" type="text/css" href="/wamei/pages/css/icons.css" /><!-- libraries -->
<link rel="stylesheet" type="text/css"href="/wamei/pages/css/lib/font-awesome.css" /><!-- this page specific styles -->
<link rel="stylesheet" href="/wamei/pages/css/compiled/personal-info.css"type="text/css" media="screen" />
<!-- this page specific styles --><!-- open sans font -->
<link href='/wamei/pages/css/open-sans-font.css' rel='stylesheet' type='text/css' /><link rel="stylesheet" type="text/css" href="/wamei/pages/js/uploadify/uploadify.css" /><!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><style type="text/css">#previewDiv{margin-left: 134px;}#previewDiv img{margin-right: 6px;margin-top:6px;}#videoFileDiv{margin-left: 134px;}#videoFileDiv a{margin-top: 15px;}#videoDiv{margin-left: 134px;}#videoDiv img{margin-right: 6px;margin-top:6px;}.image-remove-icon{position: relative;top: -36px;left: -22px;background-color: #3e4ada;}.image-remove-icon i{color:#fff;}.uploadify{height: 50px !important;}.uploadify-button{height: 25px !important;line-height: 25px !important;width: 70px !important;margin-top: 10px;}.swfupload{top: 7px;height: 45px;}.uploadify-queue{margin-top: 27px;}</style>
</head><!-- main container .wide-content is used for this layout without sidebar :)  -->
<div class="content wide-content"><div class="container-fluid"><div class="settings-wrapper" id="pad-wrapper"><div class="span7 personal-info"><div id="roleEditDiv"><h5 class="personal-title">快讯添加/编辑</h5></div><form action="/wamei/newsFlashController/save.htm" method="post" enctype="multipart/form-data" id="editForm"><input type="hidden" name="id" value="${mo.id}"/><input type="hidden" name="newsFlashStatus" value="${mo.status}"/><input type="hidden" name="createTime" value="${mo.createTimeStr}"/><div class="field-box"><label class="Validform_label">快讯类型:</label><div class="ui-select"><select id="newsFlashType" name="newsFlashType.id"><option value="">请选择</option><c:forEach items="${typeList}" var="item" varStatus="status"><option value="${item.id}">${item.name}</option></c:forEach></select></div></div><div class="field-box"><label class="Validform_label">快讯内容:</label><textarea id="content" name="content" value="${mo.content}"  datatype="/^\s*$/|*1-500"  errormsg="快讯内容至少1个字符,最多500个字符!"  style="width: 300px;height: 100px;max-width: 300px;max-height: 100px;">${mo.content}</textarea></div><div class="field-box"><label class="Validform_label">快讯图片:</label><div id="previewDiv"><img src="/wamei/pages/img/new-gallery-img.png" id="imghead" style='width:100px;height:100px;'/></div><div id="imageFile" style="display:none;"><input type="file" name="imagefile" id="hiddenFile" οnchange='previewManyImage(this,"imgFile");'/></div></div><div class="field-box"><label class="Validform_label">快讯视频:</label><div id="videoDiv"></div><div id="videoFileDiv"><input type="file" name="videoFile" id="videoFile"  /></div></div><div class="field-box"><label class="Validform_label">全文链接:</label><div class="ui-select"><select id="linkType" name="linkType" datatype="*" errormsg="请选择全文链接类型!"><option value="1">文章ID</option><option value="2" selected>H5链接</option></select></div></div><div class="field-box"><label class="Validform_label"></label><input class="span5 inline-input" type="text" value="${mo.link}" id="link" name="link" style="height: 25px"/></div><div class="field-box"><label>定时发布:</label><div class="input-append date form_datetime"><input class="span5 inline-input" type="text" id="publishTime" readonly name="publishTime" value="${mo.publishTimeStr}" style="height: 25px;width: 135%;" /><span class="add-on"><i class="icon-remove"></i></span><span class="add-on"><i class="icon-calendar"></i></span></div></div><div class="span6 field-box actions"><input type="button" class="btn-glow primary" value="提交" id="checkButton"/> <span></span><input type="button" class="btn-glow primary" value="取消" οnclick="cancle();" /></div></form></div></div></div>
</div>
<!-- end main container --><!-- scripts -->
<script src="/wamei/pages/js/jquery.min.js"></script>
<script src="/wamei/pages/js/jquery.form.js"></script>
<script src="/wamei/pages/js/bootstrap.min.js"></script>
<script src="/wamei/pages/js/bootstrap-datetimepicker.js"></script>
<script src="/wamei/pages/js/Validform_v5.3.2.js"></script>
<script type="text/javascript" src="/wamei/pages/js/uploadify/jquery.uploadify.min.js"></script>
<script src="/wamei/pages/js/theme.js"></script><script type="text/javascript">$(function() {$('#videoFile').uploadify({'swf'      : '/wamei/pages/js/uploadify/uploadify.swf','uploader' : '/wamei/newsFlashController/upload/video.htm',// Your options here'formData': {},'fileObjName' : 'videoFile','fileSizeLimit' : 0,'auto':true,'buttonText': '添加视频','fileTypeExts'  : '*.mp4;*.avi;*.3gp;*.wmv;*.flv;*.mov;*.mpeg','removeCompleted' : true,'removeTimeout' : 1,'multi' : false,'onUploadStart' : function(file) {var num = $(".videoCover").length;if(file.size>=31457280){alert("超过视频上传限制大小(30M)!");this.cancelUpload(file.id);}if(null!=num && num>4){alert("最多只能上传5个视频!");this.cancelUpload(file.id);//$('#' + file.id).remove();}},'onUploadSuccess':function(file,json,response){//console.log(file);console.log(json);var videoId = "video"+Math.floor(Math.random()*100000+1);var data = eval("(" + json + ")");if (data && data.statusCode == 1) {$("#videoDiv").append("<img src='"+data.videoConver+"' link='"+data.videoLink+"' class='videoCover "+videoId+"' οnclick='previewVideo(this);' style='width:100px;height:100px;'/>" +"<span class='image-remove-icon icon trash' videoId='"+videoId+"' title='删除' οnclick='videoRemove(this);'><i class='icon-remove'></i></span>");var videosData =data.videoConver +"@"+ data.videoLink;$("#videoFileDiv").append("<input type='hidden' class='"+videoId+"' name='videos' value='"+videosData+"' />");} else {alert(data.msg);}},'onQueueComplete' : function(json) {$('.uploadify-queue').html('');//return false;}});//快讯图片var images = '${mo.images}';if(images){var data = images.split(",");console.log(data);for(var i=0;i<data.length;i++){var imgId = "img"+i;$("#imghead").before("<img src='"+data[i]+"' class='imgFile "+imgId+"' style='width:100px;height:100px;'/>" +"<span class='image-remove-icon icon trash' imgId='"+imgId+"' title='删除' οnclick='imageRemove(this);'><i class='icon-remove'></i></span>");$("#imageFile").append("<input type='hidden' class='"+imgId+"' name='imageUrl' value='"+data[i]+"' />");}}//快讯视频var videoCover = '${mo.videoCover}';var videos = '${mo.videos}';if(videoCover){var data = videoCover.split(",");var videoData = videos.split(",");console.log(data);console.log(videoData);for(var i=0;i<data.length;i++){var videoId = "video"+i;$("#videoDiv").append("<img src='"+data[i]+"' link='"+videoData[i]+"' class='videoCover "+videoId+"' οnclick='previewVideo(this);' style='width:100px;height:100px;'/>" +"<span class='image-remove-icon icon trash' videoId='"+videoId+"' title='删除' οnclick='videoRemove(this);'><i class='icon-remove'></i></span>");var videosStr = data[i] + "@" +videoData[i];$("#videoFileDiv").append("<input type='hidden' class='"+videoId+"' name='videos' value='"+videosStr+"' />");}}$(".form_datetime").datetimepicker({format:"yyyy-mm-dd hh:ii:ss",autoclose: true,todayBtn: true,minuteStep: 10,pickerPosition: "bottom-left",minView:0});//类型选中var typeId = "${mo.newsFlashType.id}";if(typeId){$("#newsFlashType").val(typeId);}//全文链接类型var linkType = '${mo.linkType}';if(linkType) {$("#linkType").val(linkType);}//上传图片$("#imghead").on("click", function() {$("#hiddenFile").click();});$("#editForm").Validform({btnSubmit:"#checkButton",tiptype:function(msg){if(msg != '' && msg!='通过信息验证!'){alert(msg);}},tipSweep:true,beforeSubmit:function(){saveForm();return false;}});});function saveForm(){var content = $("#content").val();var imgageUrl = $("input[name='imageUrl']").val();var videoUrl = $("input[name='videos']").val();console.log(link+"======m====="+imgageUrl+"====v====="+videoUrl);if((!content) && (!videoUrl) && (!imgageUrl)){alert("快讯内容,视频,图片三项不能全为空!");return ;}$("#editForm").ajaxSubmit({type: 'post',async: false,success: function($data) {var data = eval("("+$data+")");if(data && data.statusCode==1){alert("保存信息成功!");window.location.href = "/wamei/pages/articles/newsflash_list.jsp";}else{alert(data.msg);}}});
}
function cancle(){window.history.back(-1);
}//移除图片
function imageRemove(obj){var id = $(obj).attr("imgId");$("."+id).remove();$(obj).remove();
}
//移除视频
function videoRemove(obj){var id = $(obj).attr("videoId");$("."+id).remove();$(obj).remove();
}
//视频播放
function previewVideo(obj){var videoUrl = $(obj).attr("link");var videoCover = $(obj).attr("src");window.open("/wamei/pages/articles/previewVideo.jsp?videoUrl="+videoUrl+"&videoCover="+videoCover+"");
}</script>

图片上传预览js处理逻辑:

//图片上传预览
function previewImage(file, imgHeadDivId){var exp = /.jpg$|.gif$|.png$|.bmp$|.jpeg$|.JPG$|.GIF$|.PNG$|.BMP$|.JPEG$/;if(exp.exec(file.value)==null){alert('图片格式不正确');file.outerHTML=file.outerHTML;//清空return false;} 
//  var div = document.getElementById('previewDiv');var ihId = imgHeadDivId?imgHeadDivId:'imghead';var img = document.getElementById(ihId);if (file.files && file.files[0]){  
//    	div.innerHTML = "<img id='imghead' class='avatar img-circle' style='width:100px;height:100px;'>";  var img = document.getElementById(ihId);var reader = new FileReader();  reader.onload = function(evt){img.src = evt.target.result;}  reader.readAsDataURL(file.files[0]);  }else{  var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';file.select();  var src = document.selection.createRange().text;  
//    	div.innerHTML = "<img id='imghead' class='avatar img-circle' style='width:100px;height:100px;'>";  var img = document.getElementById(ihId);img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;  
//    	div.innerHTML = "<div id='divhead' style='width:100px;height:100px;"+sFilter+src+"\"'></div>";  }  
}//多图上传
function previewManyImage(file, imgHeadDivId){var exp = /.jpg$|.gif$|.png$|.bmp$|.jpeg$|.JPG$|.GIF$|.PNG$|.BMP$|.JPEG$/;if(exp.exec(file.value)==null){alert('图片格式不正确');file.outerHTML=file.outerHTML;//清空return false;}var num = $(".imgFile").length;console.log(num);if(null!=num && num>9){alert("最多只能上传10张图片!");return ;}var ihId = imgHeadDivId?imgHeadDivId:'imghead';var img = document.getElementById(ihId);if (file.files && file.files[0]){console.log("file:"+file.files.length);var img = document.getElementById(ihId);var imgId = "img"+Math.floor(Math.random()*100000+1);var reader = new FileReader();reader.onload = function(evt){$("#imghead").before("<img src='"+evt.target.result+"' class='imgFile "+imgId+"' style='width:100px;height:100px;'/>" +"<span class='image-remove-icon icon trash' imgId='"+imgId+"' title='删除' οnclick='imageRemove(this);'><i class='icon-remove'></i></span>");}reader.readAsDataURL(file.files[0]);var formData = new FormData();formData.append('file', $('#hiddenFile')[0].files[0]);$.ajax({url : "/wamei/newsFlashController/upload/image.htm",type : 'POST',data:formData,processData : false,contentType : false,success : function($data) {var data = eval("(" + $data + ")");if (data && data.statusCode == 1) {$("#imageFile").append("<input type='hidden' class='"+imgId+"' name='imageUrl' value='"+data.result+"' />");} else {alert(data.msg);}}});}else{var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';file.select();var src = document.selection.createRange().text;var img = document.getElementById(ihId);img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;}
}


这篇关于Java 快讯功能开发记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/982806

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory