加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swfupload2_2上传视频的实现

发布时间:2020-12-15 20:11:29 所属栏目:百科 来源:网络整理
导读:1、导入jquery script type="text/javascript" src="${ctx}/js/jquery-1.10.2.min.js"/script 2、swfupload2_2文件夹引入项目。 如果视频需要转码的话,则需要引入:drv43260.dll、ffmpeg.exe、mencoder.exe、Pncrt.dll、pthreadGC2.dll这几个插件。 如果视

1、导入jquery

<script type="text/javascript" src="${ctx}/js/jquery-1.10.2.min.js"></script>

2、swfupload2_2文件夹引入项目。

如果视频需要转码的话,则需要引入:drv43260.dll、ffmpeg.exe、mencoder.exe、Pncrt.dll、pthreadGC2.dll这几个插件。

如果视频需要播放的话,需要引入播放器到项目。


<script type="text/javascript" src="${ctx}/js/swfupload2_2/swfupload.js"></script>
<script type="text/javascript" src="${ctx}/js/swfupload2_2/swfupload.queue.js"></script>
<script type="text/javascript" src="${ctx}/js/swfupload2_2/fileprogress.js"></script>
<script type="text/javascript" src="${ctx}/js/swfupload2_2/handlers.js"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/js/swfupload2_2/swfupload.css" />

<script type="text/javascript">
$(function() {
var swfupload;
var setting = {
flash_url : "${ctx}/js/swfupload2_2/swfupload.swf",
upload_url : "${ctx}/console/video/addSave/;jsessionid=${sessionId}",

//jsessionid是为了在火狐、谷歌也可以上传,在返回此页面的方法内获取一下sessionId---》setAttr("sessionId",getSession().getId());
file_post_name : "Filedata",//后台获取视频的name
file_size_limit : "100MB",//最大视频限制
file_types : "*.wmv9;*.rm;*.rmvb;*.mpg;*.wmv;*.3gp;*.mov;*.mp4;*.asf;*.flv;*.avi",//上传视频的格式
file_types_description : "视频文件",
file_upload_limit : 1,//上传个数
file_queue_limit : 1,
custom_settings : {
progressTarget : "fsUploadProgress"
},
debug : false,


// Button settings
button_action : SWFUpload.BUTTON_ACTION.SELECT_FILE,
button_image_url : "${ctx}/js/swfupload2_2/background.png",
button_width : "65",
button_height : "30",
button_placeholder_id : "video",//隐藏
button_text : '<span class="theFont">选择文件</span>',
button_text_style : ".theFont { font-size: 12; }",
button_text_left_padding : 7,
button_text_top_padding : 5,


// The event handler functions are defined in handlers.js
file_queued_handler : selfFileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_start_handler : uploadStart,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : selfUploadComplete,
queue_complete_handler : queueComplete
// Queue plugin event
};
swfupload = new SWFUpload(setting);
$("#sub").bind("click",function(event) {
var na = $("#videoName").val();
var stid = $("#stid").val();
var videoid=$("#videoid").val();
if(videoid==null||videoid==""){
if(na==null || na==""){
alert("视频名称不允许为空!");
}else{
swfupload.addPostParam("videoName",na);
swfupload.addPostParam("stid",stid);
swfupload.startUpload();
}
}
if(videoid.length>0){
swfupload.addPostParam("videoName",stid);
swfupload.addPostParam("videoId",videoid);
swfupload.startUpload();
}?
});
//视频上传完成
function selfUploadComplete() {
window.location.href = "${ctx}/console/video";
}
function selfFileQueued(file) {
try {
var progress = new FileProgress(file,
this.customSettings.progressTarget);
progress.setStatus("等待...");
progress.toggleCancel(true,this);
$("#videoName").val(file.name.split(".")[0]);
} catch (ex) {
this.debug(ex);
}
}
});
</script>

---------------------------------------核心代码

<table>

<tr>
<td class="tdo">视频名称:</td>
<td class="tdt">
<input type="text" size="60" class="inputText Required" id="videoName" value="${video.vname }" name="file" /> <span><font id="names" color="red"></font> </span>
</td>
</tr>
<tr>
<td class="tdo">视频源文件:</td>
<td class="tdt">
<c:if test="${video.vid!=null }">
<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'?
codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0'?
width='516' height='425' id='player' align='middle'>
<param name='allowScriptAccess' value='sameDomain' />
<param name='movie' value='${ctx }/js/player.swf'/>
<param name='quality' value='high' />
<param name='allowfullscreen' value='true'/>
<param name='wmode' value='transparent'/>
<param name='FlashVars' value='file=${ctx }/upload/video/${video.file}'/>
<embed src='${ctx }/js/player.swf' FlashVars='file=${ctx }/upload/video/${video.file}'?
quality='high' wmode='transparent' width='516' height='425' align='middle' allowscriptaccess='sameDomain'?
allowfullscreen='true'type='application/x-shockwave-flash'pluginspage='http://www.macromedia.com/go/getflashplayer' />
</object><br/>
</c:if>
<span id="video" ></span>
<div id="fsUploadProgress" ></div>
</td>
</tr>
</table>
<div align="center">
<span class="btn" id="sub">上传视频</span>



3、后台程序:

UploadFile uf = getFile("Filedata",PathKit.getWebRootPath() + "/" + VIDEO_RESOURCE_VIDEO_DIR,1003 * 10240 * 10240);//视频名称和存放路径
String name = uf.getFileName();
String hzn = name.substring(name.lastIndexOf(".") + 1);//后缀
name = time.getTime().replace("-","").replace(":","").replace(" ","") + "." + hzn;
String srcname = uf.getFileName().substring(0,uf.getFileName().length() - hzn.length() - 1);
if(getPara("videoId")==null||getPara("videoId").trim().length()<=0){
Video video=getModel(ClubVideo.class);
video.set("st_id",getPara("stid") );
video.set("file",name);
video.set("vname",srcname);
video.set("img","");
video.set("vtime","");
video.set("state",0);// 0等待转码 1转码成功 2转码失败
video.save();
File ff = new File(PathKit.getWebRootPath() + "" + VIDEO_RESOURCE_VIDEO_DIR + "" + video.getStr("file"));
uf.getFile().renameTo(ff);
Video2FlvThread t = new Video2FlvThread(video,video.getInt("vid"),PathKit.getWebRootPath() + "",VIDEO_RESOURCE_VIDEO_DIR,""
+ video.getStr("file"),0);
ThreadPool.addToFixedPool(t);
}




4、视频转码的class



public class Video2FlvThread implements Runnable {

//参数
private int videoId;
private String appPath;
private String filePath;
private String path;
private String imgpath;
private String videoTime;// 视频时长
private ClubVideo clubVideo;
private String fileName;
private int a;


/**
* 视频转码线程,转码成功后, 更新视频信息转码状态
*?
* @param dao 数据库工具
* @param videoInfoId 视频信息ID
* @param appPath 应用目录 D:******
* @param filePath 存储目录 ****
*/
public Video2FlvThread(ClubVideo video,Integer videoInfoId,String appPath,String filePath,String filename,Integer a) {
this.clubVideo = video;
this.videoId = videoInfoId;
this.appPath = appPath.replace("/","");
this.filePath = filePath.replace("/","");
this.fileName = filename;
this.a = a;//判断是否截图
}


public void run() {
clubVideo.find("select * from club_video where vid=" + videoId);
path = (appPath + filePath).replace("/","") + "";
imgpath = appPath + "uploadimages";
if (clubVideo != null && new File(appPath + filePath + fileName).exists()) {// 记录不为空,且文件存在


String flvFile = clubVideo.getStr("file");
String imgFile = clubVideo.getStr("img");
String newFileId = Id.getFileID();
flvFile = newFileId + ".flv";
imgFile = newFileId + ".jpg";
if (flvFile != null && flvFile.trim().length() > 0) {// 已经转过码,删除旧文件,
new File(path + flvFile).delete();
}
if (imgFile != null && imgFile.trim().length() > 0) {// 删除旧图片
new File(imgpath + imgFile).delete();
}


// 开始转码
// 1、更新状态
clubVideo.set("state",1);// 转码中
clubVideo.update();
// 2、判断类型
int type = checkContentType();
if (type == -1) {// 不支持的类型
clubVideo.set("state",3);// 转码失败
clubVideo.update();
} else {// 支持的类型
boolean r = false;
if (type == 0) {// 直接转成FLV
r = convertToFLV(fileName,flvFile);
if (r) {
if (fileName != null && fileName.trim().length() > 0) {// ?删除 旧 文件,
new File(appPath + filePath + fileName).delete();
}
}
} else if (type == 1) {// 先转AVI,再转FLV
String aviFile = newFileId + ".avi";
if (convertToAVI(aviFile)) {// AVI转成功,且文件存在
r = convertToFLV(fileName,flvFile);
// 转完后,删除AVI
if (r) {
new File(path + aviFile).delete();
}
}
} else if (type == 2) {// FLV格式
r = true;
// flvFile = fileName;// 用原文件进行截图
}
if (r) {// flv转成功
// 提取缩略图
if(a==0){
if (processImg(flvFile,imgFile)) {
clubVideo.set("img",imgFile);
}
}
if (videoTime != null && videoTime.trim().length() > 0) {// 视频时长
videoTime = videoTime.substring(0,8);
if (videoTime.substring(0,3).equals("00:")) {
videoTime = videoTime.substring(3,8);
}
clubVideo.set("vtime",videoTime);
}
// 更新状态
clubVideo.set("state",2);
clubVideo.set("file",flvFile);
clubVideo.update();
} else {// FLV转码失败
clubVideo.set("state",3);// 转码失败
clubVideo.update();
File ff = new File(PathKit.getWebRootPath()+""
+"uploadtemp"+""+clubVideo.getStr("vname"));

Random random = new Random(9);
? ?int a=0;
? ?for(int i = 0;i <10;i++){
? ? ? ?a=random.nextInt();
? ?}

File file=new File(PathKit.getWebRootPath()+""
+"uploadtemp"+""+a+".flv");
ff.renameTo(file);
}


}
}


}


/**
* 验证原文件格式
*?
* @return 0:支持直接转到FLV,1: 由Mencoder转后再到FLV,-1:不支持的格式
*/
private int checkContentType() {
String type = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length()).toLowerCase();
if (type.equals("avi")) {// 以下格式,直接转到flv
return 0;
} else if (type.equals("mpg")) {
return 0;
} else if (type.equals("wmv")) {
return 0;
} else if (type.equals("3gp")) {
return 0;
} else if (type.equals("mov")) {
return 0;
} else if (type.equals("mp4")) {
return 0;
} else if (type.equals("asf")) {
return 0;
} else if (type.equals("asx")) {
return 0;
} else if (type.equals("flv")) {
return 0;
} else if (type.equals("wmv9")) {// 如果是wmv9,rm,rmvb用mencoder转avi再由ffmpeg解析
return 1;
} else if (type.equals("rm")) {
return 1;
} else if (type.equals("rmvb")) {
return 1;
} else {// 格式不支持
return -1;
}
}


/**
* 转码AVI
*?
* @param aviFile
* @return
*/
private boolean convertToAVI(String aviFile) {
boolean b = false;
List<String> commend = new java.util.ArrayList<String>();
commend.add(appPath + "tool" + "mencoder");
commend.add(appPath + filePath + fileName);
commend.add("-oac");// 输出音频编码
commend.add("lavc");
commend.add("-lavcopts");
commend.add("acodec=mp3:abitrate=64");
commend.add("-ovc");
commend.add("xvid");
commend.add("-xvidencopts");
commend.add("bitrate=600");
commend.add("-of");
commend.add("avi");
commend.add("-o");
commend.add(path + aviFile);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process p = builder.start();


BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
// System.out.println(line);
}
p.waitFor();
// AVI文件存在时,返回TRUE
if (new File(path + aviFile).exists()) {
b = true;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("转码到avi:" + filePath + fileName + "失败!");
} finally {
return b;
}
}


/**
* 转FLV
*?
* @param srcFileName 源文件
* @param flvFileName 目标文件
* @return
*/
private boolean convertToFLV(String fileName,String flvName) {
boolean b = false;
List<String> commend = new java.util.ArrayList<String>();


commend.add(appPath + "tool" + "ffmpeg");
commend.add("-i");
commend.add(path + fileName);
commend.add("-ab");// 音频数据流量 32、64、96、128
commend.add("32");
// commend.add("-qscale");// 以<数值>为质量,取值0.01-255,约小质量越好
// commend.add("6");
commend.add("-acodec");// 音频编码
commend.add("mp3");
commend.add("-ac");// 声道数
commend.add("2");
commend.add("-ar");// 声音采样率
commend.add("22050");
commend.add("-b:v");// 比特率
commend.add( "200k");
commend.add("-r");// 桢速率
commend.add( "200");
commend.add("-s");//分辨率
commend.add("700*500");
commend.add("-y");// 覆盖输出文件
commend.add(path ?+ flvName);
try {
String regexDuration = "Duration: (.*?),start: (.*?),bitrate: (d*) kb/s";
Pattern pattern = Pattern.compile(regexDuration);


ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process p = builder.start();


BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
Matcher m = pattern.matcher(line);
if (m.find()) {
videoTime = m.group(1);
}
// System.out.println(line);//查看转码情况进度
}
p.waitFor();
// 验证文件
if (new File(path + flvName).exists()) {
b = true;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("转码到flv:" + filePath + fileName + "失败!");
} finally {
return b;
}
}


/**
* 生成缩略图
*?
* @param flvFileName
* @param picFileName
* @return
*/
private boolean processImg(String flvFileName,String picFileName) {
List<String> commend = new ArrayList<String>();
commend.add(appPath + "tool" + "ffmpeg");
commend.add("-ss");
commend.add("1");
commend.add("-i");
commend.add(path + flvFileName);
commend.add("-y");
commend.add("-f");
commend.add("image2");
commend.add("-t");
commend.add("0.001");
commend.add("-s");
commend.add("860*480");
commend.add(imgpath + picFileName);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process p = builder.start();


BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
// System.out.println(line);
}
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
System.out.println("从flv取截图:" + filePath + flvFileName + "失败!");
} finally {
return true;
}
}


public int getA() {
return a;
}


public void setA(int a) {
this.a = a;
}


}

5、线程池:

/** ?* 线程池 ?*? ?* @author Administrator ?*? ?*/ public class ThreadPool { private static ExecutorService singlePool = Executors.newSingleThreadExecutor(); private static ExecutorService cachedPool = Executors.newCachedThreadPool(); private static ExecutorService fixedPool = Executors.newFixedThreadPool(5); /* * 检测 */ public static void execute(Runnable run) { fixedPool.execute(run); } public static void shutdown() { fixedPool.shutdown(); } /** * 添加到顺序线程池中执行 *? * @param t */ public static void addToSinglePool(Runnable t) { singlePool.execute(t); } /** * 添加到并发线程池执行 *? * @param t */ public static void addToCachedPool(Runnable t) { cachedPool.execute(t); } /** * 添加到定长线程池 *? * @param t */ public static void addToFixedPool(Runnable t) { fixedPool.execute(t); } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读