Java上传视频实例代码
页面:
上传文件时的关键词:enctype="multipart/form-data"
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
"rel="externalnofollow">
上传视频
文件上传
文件上传
后台:
controller
importjavax.servlet.http.HttpServletRequest;
importmodel.FileEntity;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.ModelMap;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.ResponseBody;
importorg.springframework.web.multipart.MultipartFile;
importorg.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/uploadflv")
publicclassUploadController{
@RequestMapping(value="/upload",method={RequestMethod.POST,RequestMethod.GET})
@ResponseBody
publicModelAndViewupload(@RequestParam(value="file",required=false)MultipartFilemultipartFile,
HttpServletRequestrequest,ModelMapmap){
Stringmessage="";
FileEntityentity=newFileEntity();
FileUploadToolfileUploadTool=newFileUploadTool();
try{
entity=fileUploadTool.createFile(multipartFile,request);
if(entity!=null){
//service.saveFile(entity);
message="上传成功";
map.put("entity",entity);
map.put("result",message);
}else{
message="上传失败";
map.put("result",message);
}
}catch(Exceptione){
e.printStackTrace();
}
returnnewModelAndView("result",map);
}
}
工具类
importjava.io.File;
importjava.io.IOException;
importjava.sql.Timestamp;
importjava.text.DecimalFormat;
importjava.util.Arrays;
importjava.util.Iterator;
importjavax.servlet.http.HttpServletRequest;
importmodel.FileEntity;
importorg.springframework.web.multipart.MultipartFile;
publicclassFileUploadTool{
TransfMediaTooltransfMediaTool=newTransfMediaTool();
//文件最大500M
privatestaticlongupload_maxsize=800*1024*1024;
//文件允许格式
privatestaticString[]allowFiles={".rar",".doc",".docx",".zip",
".pdf",".txt",".swf",".xlsx",".gif",".png",".jpg",".jpeg",
".bmp",".xls",".mp4",".flv",".ppt",".avi",".mpg",".wmv",
".3gp",".mov",".asf",".asx",".vob",".wmv9",".rm",".rmvb"};
//允许转码的视频格式(ffmpeg)
privatestaticString[]allowFLV={".avi",".mpg",".wmv",".3gp",
".mov",".asf",".asx",".vob"};
//允许的视频转码格式(mencoder)
privatestaticString[]allowAVI={".wmv9",".rm",".rmvb"};
publicFileEntitycreateFile(MultipartFilemultipartFile,HttpServletRequestrequest){
FileEntityentity=newFileEntity();
booleanbflag=false;
StringfileName=multipartFile.getOriginalFilename().toString();
//判断文件不为空
if(multipartFile.getSize()!=0&&!multipartFile.isEmpty()){
bflag=true;
//判断文件大小
if(multipartFile.getSize()<=upload_maxsize){
bflag=true;
//文件类型判断
if(this.checkFileType(fileName)){
bflag=true;
}else{
bflag=false;
System.out.println("文件类型不允许");
}
}else{
bflag=false;
System.out.println("文件大小超范围");
}
}else{
bflag=false;
System.out.println("文件为空");
}
if(bflag){
StringlogoPathDir="/video/";
StringlogoRealPathDir=request.getSession().getServletContext().getRealPath(logoPathDir);
//上传到本地磁盘
//StringlogoRealPathDir="E:/upload";
FilelogoSaveFile=newFile(logoRealPathDir);
if(!logoSaveFile.exists()){
logoSaveFile.mkdirs();
}
Stringname=fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("文件名称:"+name);
//新的文件名
StringnewFileName=this.getName(fileName);
//文件扩展名
StringfileEnd=this.getFileExt(fileName);
//绝对路径
StringfileNamedirs=logoRealPathDir+File.separator+newFileName+fileEnd;
System.out.println("保存的绝对路径:"+fileNamedirs);
Filefiledirs=newFile(fileNamedirs);
//转入文件
try{
multipartFile.transferTo(filedirs);
}catch(IllegalStateExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
//相对路径
entity.setType(fileEnd);
StringfileDir=logoPathDir+newFileName+fileEnd;
StringBuilderbuilder=newStringBuilder(fileDir);
StringfinalFileDir=builder.substring(1);
//size存储为String
Stringsize=this.getSize(filedirs);
//源文件保存路径
StringaviPath=filedirs.getAbsolutePath();
//转码Avi
//booleanflag=false;
if(this.checkAVIType(fileEnd)){
//设置转换为AVI格式后文件的保存路径
StringcodcAviPath=logoRealPathDir+File.separator+newFileName+".avi";
//获取配置的转换工具(mencoder.exe)的存放路径
StringmencoderPath=request.getSession().getServletContext().getRealPath("/tools/mencoder.exe");
aviPath=transfMediaTool.processAVI(mencoderPath,filedirs.getAbsolutePath(),codcAviPath);
fileEnd=this.getFileExt(codcAviPath);
}
if(aviPath!=null){
//转码Flv
if(this.checkMediaType(fileEnd)){
try{
//设置转换为flv格式后文件的保存路径
StringcodcFilePath=logoRealPathDir+File.separator+newFileName+".flv";
//获取配置的转换工具(ffmpeg.exe)的存放路径
StringffmpegPath=request.getSession().getServletContext().getRealPath("/tools/ffmpeg.exe");
transfMediaTool.processFLV(ffmpegPath,aviPath,codcFilePath);
fileDir=logoPathDir+newFileName+".flv";
builder=newStringBuilder(fileDir);
finalFileDir=builder.substring(1);
}catch(Exceptione){
e.printStackTrace();
}
}
entity.setSize(size);
entity.setPath(finalFileDir);
entity.setTitleOrig(name);
entity.setTitleAlter(newFileName);
Timestamptimestamp=newTimestamp(System.currentTimeMillis());
entity.setUploadTime(timestamp);
returnentity;
}else{
returnnull;
}
}else{
returnnull;
}
}
/**
*文件类型判断
*
*@paramfileName
*@return
*/
privatebooleancheckFileType(StringfileName){
Iteratortype=Arrays.asList(allowFiles).iterator();
while(type.hasNext()){
Stringext=type.next();
if(fileName.toLowerCase().endsWith(ext)){
returntrue;
}
}
returnfalse;
}
/**
*视频类型判断(flv)
*
*@paramfileName
*@return
*/
privatebooleancheckMediaType(StringfileEnd){
Iteratortype=Arrays.asList(allowFLV).iterator();
while(type.hasNext()){
Stringext=type.next();
if(fileEnd.equals(ext)){
returntrue;
}
}
returnfalse;
}
/**
*视频类型判断(AVI)
*
*@paramfileName
*@return
*/
privatebooleancheckAVIType(StringfileEnd){
Iteratortype=Arrays.asList(allowAVI).iterator();
while(type.hasNext()){
Stringext=type.next();
if(fileEnd.equals(ext)){
returntrue;
}
}
returnfalse;
}
/**
*获取文件扩展名
*
*@returnstring
*/
privateStringgetFileExt(StringfileName){
returnfileName.substring(fileName.lastIndexOf("."));
}
/**
*依据原始文件名生成新文件名
*@return
*/
privateStringgetName(StringfileName){
Iteratortype=Arrays.asList(allowFiles).iterator();
while(type.hasNext()){
Stringext=type.next();
if(fileName.contains(ext)){
StringnewFileName=fileName.substring(0,fileName.lastIndexOf(ext));
returnnewFileName;
}
}
return"";
}
/**
*文件大小,返回kb.mb
*
*@return
*/
privateStringgetSize(Filefile){
Stringsize="";
longfileLength=file.length();
DecimalFormatdf=newDecimalFormat("#.00");
if(fileLength<1024){
size=df.format((double)fileLength)+"BT";
}elseif(fileLength<1048576){
size=df.format((double)fileLength/1024)+"KB";
}elseif(fileLength<1073741824){
size=df.format((double)fileLength/1048576)+"MB";
}else{
size=df.format((double)fileLength/1073741824)+"GB";
}
returnsize;
}
}
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.ArrayList;
importjava.util.List;
publicclassTransfMediaTool{
/**
*视频转码flv
*
*@paramffmpegPath
*转码工具的存放路径
*@paramupFilePath
*用于指定要转换格式的文件,要截图的视频源文件
*@paramcodcFilePath
*格式转换后的的文件保存路径
*@return
*@throwsException
*/
publicvoidprocessFLV(StringffmpegPath,StringupFilePath,StringcodcFilePath){
//创建一个List集合来保存转换视频文件为flv格式的命令
Listconvert=newArrayList();
convert.add(ffmpegPath);//添加转换工具路径
convert.add("-i");//添加参数"-i",该参数指定要转换的文件
convert.add(upFilePath);//添加要转换格式的视频文件的路径
convert.add("-ab");
convert.add("56");
convert.add("-ar");
convert.add("22050");
convert.add("-q:a");
convert.add("8");
convert.add("-r");
convert.add("15");
convert.add("-s");
convert.add("600*500");
/*
*convert.add("-qscale");//指定转换的质量convert.add("6");
*convert.add("-ab");//设置音频码率convert.add("64");convert.add("-ac");
*//设置声道数convert.add("2");convert.add("-ar");//设置声音的采样频率
*convert.add("22050");convert.add("-r");//设置帧频convert.add("24");
*convert.add("-y");//添加参数"-y",该参数指定将覆盖已存在的文件
*/
convert.add(codcFilePath);
try{
ProcessvideoProcess=newProcessBuilder(convert).redirectErrorStream(true).start();
newPrintStream(videoProcess.getInputStream()).start();
videoProcess.waitFor();
}catch(IOExceptione1){
e1.printStackTrace();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
/**
*对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),先用mencoder转换为avi(ffmpeg能解析的)格式
*
*@parammencoderPath
*转码工具的存放路径
*@paramupFilePath
*用于指定要转换格式的文件,要截图的视频源文件
*@paramcodcFilePath
*格式转换后的的文件保存路径
*@return
*@throwsException
*/
publicStringprocessAVI(StringmencoderPath,StringupFilePath,StringcodcAviPath){
//booleanflag=false;
Listcommend=newArrayList();
commend.add(mencoderPath);
commend.add(upFilePath);
commend.add("-oac");
commend.add("mp3lame");
commend.add("-lameopts");
commend.add("preset=64");
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(codcAviPath);
try{
//预处理进程
ProcessBuilderbuilder=newProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
//进程信息输出到控制台
Processp=builder.start();
BufferedReaderbr=newBufferedReader(newInputStreamReader(p.getInputStream()));
Stringline=null;
while((line=br.readLine())!=null){
System.out.println(line);
}
p.waitFor();//直到上面的命令执行完,才向下执行
returncodcAviPath;
}catch(Exceptione){
e.printStackTrace();
returnnull;
}
}
}
classPrintStreamextendsThread{
java.io.InputStream__is=null;
publicPrintStream(java.io.InputStreamis){
__is=is;
}
publicvoidrun(){
try{
while(this!=null){
int_ch=__is.read();
if(_ch!=-1)
System.out.print((char)_ch);
else
break;
}
}catch(Exceptione){
e.printStackTrace();
}
}
}
实体类
importjava.sql.Timestamp;
publicclassFileEntity{
privateStringtype;
privateStringsize;
privateStringpath;
privateStringtitleOrig;
privateStringtitleAlter;
privateTimestampuploadTime;
publicStringgetType(){
returntype;
}
publicvoidsetType(Stringtype){
this.type=type;
}
publicStringgetSize(){
returnsize;
}
publicvoidsetSize(Stringsize){
this.size=size;
}
publicStringgetPath(){
returnpath;
}
publicvoidsetPath(Stringpath){
this.path=path;
}
publicStringgetTitleOrig(){
returntitleOrig;
}
publicvoidsetTitleOrig(StringtitleOrig){
this.titleOrig=titleOrig;
}
publicStringgetTitleAlter(){
returntitleAlter;
}
publicvoidsetTitleAlter(StringtitleAlter){
this.titleAlter=titleAlter;
}
publicTimestampgetUploadTime(){
returnuploadTime;
}
publicvoidsetUploadTime(TimestampuploadTime){
this.uploadTime=uploadTime;
}
}
总结
以上所述是小编给大家介绍的Java上传视频实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!