页面:
上传文件时的关键词:enctype = "multipart/form-data"
<%@ page Language = "java" import = "java.util。*" pageencoding = "utf-8"%> <%string path = request.getContextPath(); string basepath = request.getscheme()+"://"+request.getServername()+":"+request.getServerport()+path+"/";%> <!<!<!<!<! nofollow "> <title>上传视频</title> <meta http-equiv =" pragma "content =" no-cache "> <meta http-equiv =" cache-control "content =" no-cache "> <meta http-equiv =" expires "content =" 0 " <メタhttp-equiv = "description" content = "これは私のページです"> </head> <body> <div> <div> <div align = "center"> <h1>文件上传</h1> </div> <hr> <form id = "upload" method = "post" action = "uploadflv/upload.do" enctype = "> < <div> <入力タイプ= "ファイル" name = "file" id = "file"> <br> <入力タイプ= "" value = "上传"> </div> </div> </form> </div> </div> </body> </html> </form
后台:
コントローラ
javax.servlet.http.httpservletrequest; Import model.fileentity; Import org.springframework.stereotype.controller; Import org.springframework.ui.modelmap; Import org.springframework.web.bind.annotation.Requestmapping; requestmapping; org.springframework.web.bind.annotation.RequestMethod; Import org.springframework.web.bind.annotation.RequestParam; Import org.springframework.web.bind.annotation.AnsponseBody; Import org.springframework.web.web.multipart.multipartfide wab.servlet.modelandview;@controller@requestmapping( "/uploadflv")public class uploadcontroller {@requestMapping(value = "/upload"、method = {requestmethod.post、requestmethod.get})@responsebodybodybodybody bowing bowing updview "、" filed "、filed MultiPartFile MultiPartFile、httpservletrequestリクエスト、ModelMap Map){String Message = ""; fileEntity entity = new fileEntity(); fileuploadtool fileuploadtool = new fileuploadtool(); 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(例外e){e.printstacktrace(); } new ModelandView( "result"、map)を返します。 }}工具类
java.io.file;インポートjava.io.ioexception; Import java.sql.timestamp; Import java.text.decimalformat; Import java.util.arrays; Import java.util.iterator; Import javax.servlet.http.httpserprequest; Import model.filetrequest; org.springframework.web.multipart.multipartfile; public class fileuploadtool {transfmediatool transfmediatool = new transfmediatool(); // // private static string [] allowfiles = {".rar"、 ".doc"、 ".docx"、 ".zip"、 ".pdf"、 ".txt"、 ".swf"、 ".xlsx"、 ".gif" .png "、" .jpg "、"。 ".flv"、 ".ppt"、 ".avi"、 ".mpg"、 ".wmv"、 ".3gp"、 ".mov"、 ".asf"、 ".asx"、 ".vob"、 ".wmv9"、 ".rm"、 ".rmvb"}; // ffmpeg)private static string [] aoptflv = {".avi"、 ".mpg"、 ".wmv"、 ".3gp"、 ".mov"、 ".asf"、 ".asx"、 ".vob"}; //允许的视频转码格式(mencoder)private static string [] alwavi = {".wmv9"、 ".rm"、 ".rmvb"}; public fileentity createfile(multipartfile multipartfile、httpservletrequest request){fileentity entity = new fileentity(); boolean bflag = false; string filename = 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){string logopathdir = "/video/"; string logorealpathdir = request.getSession()。getServletContext()。getRealPath(logopathdir); //上传到本地磁盘// string logorealpathdir = "e:/upload";ファイルlogosavefile = new file(logorealpathdir); if(!logosavefile.exists()){logosavefile.mkdirs(); } string name = filename.substring(0、filename.lastindexof( "。")); system.out.println( "文件名称:" + name); //新的文件名文字列newFileName = this.getName(filename); //文件扩展名文字列fileend = this.getFileExt(filename); //绝对路径文字列filenAmedirs = logorealpathdir + file.separator + newFileName + fileEnd; System.out.println( "保存的绝对路径:" + filenamedirs); file filedirs = new file(filenamedirs); // try {multipartfile.transferto(filedirs); } catch(IllegalStateException e){e.printstacktrace(); } catch(ioexception e){e.printstacktrace(); } // string filedir = logopathdir + newFileName + fileEnd; StringBuilder Builder = new StringBuilder(filedir);文字列finalfiledir = builder.substring(1); //サイズ存储为文字列サイズ= this.getSize(filedirs); //源文件保存路径文字列avipath = filedirs.getabsolutepath(); //转码avi // boolean flag = false; if(this.checkavitype(fileend)){// // mencoder.exe avipath = transfmediatool.processavi(mencoderpath、filedirs.getabsolutepath()、codcavipath); fileend = this.getFileExt(codcavipath); } if(Avipath!= null){// // 获取配置的转换工具(ffmpeg.exe transfmediatool.processflv(ffmpegpath、avipath、codcfilepath); filedir = logopathdir + newFileName + ".flv"; Builder = new StringBuilder(filedir); finalfiledir = builder.substring(1); } catch(Exception e){e.printstacktrace(); }} entity.setsize(size); entity.setPath(finalfiledir); entity.settitleorig(name); entity.settitlealter(newFileName);タイムスタンプタイムスタンプ=新しいタイムスタンプ(System.CurrentTimemillis()); entity.setuploadtime(タイムスタンプ);リターンエンティティ。 } else {return null; }} else {return null; }} / ** * * * * @param filename * @return * / private boolean checkfiletype(string filename){iterator <string> type = arrays.aslist(allowfiles).iterator(); while(type.hasnext()){string ext = type.next(); if(filename.tolowercase()。endswith(ext)){return true; }} falseを返します。 } / ** *视频类型判断(flv) * * @param filename * @return * / private boolean checkmediatype(string fileend){iterator <string> type = arrays.aslist(approfflv).iterator(); while(type.hasnext()){string ext = type.next(); if(fileend.equals(ext)){return true; }} falseを返します。 } / ** *视频类型判断(avi) * * @param filename * @return * / private boolean checkavitype(string fileend){iterator <string> type = arrays.aslist(awtoavi).iterator(); while(type.hasnext()){string ext = type.next(); if(fileend.equals(ext)){return true; }} falseを返します。 } / ** *获取文件扩展名 * * @return string * / private string getFileext(string filename){return filename.substring(filename.lastindexof( "。")); } / ** *依据原始文件名生成新文件名 * @return * / private string getName(string filename){iterator <string> type = arrays.aslist(aoptfiles).iterator(); while(type.hasnext()){string ext = type.next(); if(filename.contains(ext)){string newFileName = filename.substring(0、filename.lastIndexof(ext)); NewFileNameを返します。 } } 戻る ""; } / ** *文件大小、返回kb.mb * * @return * / private string getsize(file file){string size = ""; long filelength = file.length(); Decimalformat df = new DecimalFormat( "#。00"); if(filelength <1024){size = df.format((double)filelength) + "bt"; } else if(filelength <1048576){size = df.format((double)filelength / 1024) + "kb"; } else if(filelength <1073741824){size = df.format((double)filelength / 1048576) + "mb"; } else {size = df.format(((double)filelength / 1073741824) + "gb"; } return size; }} Import java.io.bufferedReader; Import java.io.ioexception; Import java.io.inputStreamReader; Import java.util.arrayList; Import Java.util.list; public class transfmediatool { / * * *视频转码flv * * @paramffmpegpath * codcfilepath * @return * @throws例外 */ public void processflv(string ffmpegpath、string upfilepath、string codcfilepath){//创建一个リスト集合来保存转换视频文件为flv格式的命令リスト<文字列> convert = new arraylist <string>(); 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 {process videoprocess = new processBuilder(convert).redirecterrorStream(true).start(); new PrintStream(videoprocess.getInputStream())。start(); videoprocess.waitfor(); } catch(ioexception e1){e1.printstacktrace(); } catch(arturnedexception e){e.printstacktrace(); }} / ** *对ffmpeg(wmv9、rm、rmvb等)、先用mencoder转换为avi(ffmpeg能解析的)格式 * * @param mencoderpath *转码工具的存放路径 * @param upfilepath *用于指定要转换格式的文件 *用于指定要转换格式的文件 * @param MencoderPath、String upfilepath、String codcavipath){// boolean flag = false; list <string> commend = new ArrayList <String>(); 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 {// Builder.Command(称賛); Builder.redirecterrorStream(true); //进程信息输出到控制台プロセスp = builder.start(); BufferedReader br = new BufferedReader(new inputStreamReader(p.getInputStream()));文字列line = null; while((line = br.readline())!= null){system.out.println(line); } p.waitfor(); //直到上面的命令执行完、才向下执行codcavipathを返します。 } catch(Exception e){e.printstacktrace(); nullを返します。 }}} class printStream extends thread {java.io.inputStream __is = null; public PrintStream(java.io.inputStream is){__is = is; } public void run(){try {while(this!= null){int _ch = __is.read(); if(_ch!= -1)system.out.print((char)_ch);それ以外の場合は休憩します。 }} catch(例外e){e.printstacktrace(); }}}实体类
import java.sql.timestamp; public class fileentity {private string type;プライベート文字列サイズ。プライベートストリングパス。プライベートストリングタイトルリッグ;プライベートストリングタイトルーター。プライベートタイムスタンプアップロード時間。 public string getType(){return type; } public void setType(string type){this.type = type; } public string getsize(){return size; } public void setSize(string size){this.size = size; } public string getPath(){return path; } public void setPath(string path){this.path = path; } public string getTitleOrig(){return titpiteorig; } public void settitleorig(string titleorig){this.titleorig = titleorig; } public string getTitLealter(){return titlealter; } public void SettitLealter(String TitleAlter){this.titlealter = titlealter; } public Timestamp getuploadtime(){return uploadtime; } public void setuploadtime(Timestamp Uploadtime){this.uploadtime = uploadtime; }}总结
以上所述是小编给大家介绍的java上传视频实例代码、希望对大家有所帮助、如果大家有任何疑问请给我留言、小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!