Java上传视频实例代码
程序员文章站
2023-12-18 17:02:34
页面:
上传文件时的关键词:enctype="multipart/form-data"
<%@ page language="java" import="...
页面:
上传文件时的关键词: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+"/"; %> <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <base href="<%=basepath%>" rel="external nofollow" > <title>上传视频</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> </head> <body> <div class="panel panel-default"> <div class="panel-body"> <div class="panel-heading" align="center"><h1 class="sub-header h3">文件上传</h1></div> <hr> <form class="form-horizontal" id="upload" method="post" action="uploadflv/upload.do" enctype="multipart/form-data"> <div class="form-group" align="center"> <div class="col-md-4 col-sm-4 col-xs-4 col-lg-4">文件上传 <input type="file" class="form-control" name="file" id="file"><br> <input type="submit" value="上传"> </div> </div> </form> </div> </div> </body> </html>
后台:
controller
import javax.servlet.http.httpservletrequest; import model.fileentity; import org.springframework.stereotype.controller; import org.springframework.ui.modelmap; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.responsebody; import org.springframework.web.multipart.multipartfile; import org.springframework.web.servlet.modelandview; @controller @requestmapping("/uploadflv") public class uploadcontroller { @requestmapping(value = "/upload", method={requestmethod.post,requestmethod.get}) @responsebody public modelandview upload(@requestparam(value = "file", required = false) multipartfile multipartfile, httpservletrequest request, 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 (exception e) { e.printstacktrace(); } return new modelandview("result", map); } }
工具类
import java.io.file; import java.io.ioexception; import java.sql.timestamp; import java.text.decimalformat; import java.util.arrays; import java.util.iterator; import javax.servlet.http.httpservletrequest; import model.fileentity; import org.springframework.web.multipart.multipartfile; public class fileuploadtool { transfmediatool transfmediatool = new transfmediatool(); // 文件最大500m private static long upload_maxsize = 800 * 1024 * 1024; // 文件允许格式 private static string[] 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) private static string[] allowflv = { ".avi", ".mpg", ".wmv", ".3gp", ".mov", ".asf", ".asx", ".vob" }; // 允许的视频转码格式(mencoder) private static string[] allowavi = { ".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"; file logosavefile = new file(logorealpathdir); if (!logosavefile.exists()) { logosavefile.mkdirs(); } string name = filename.substring(0, filename.lastindexof(".")); system.out.println("文件名称:" + name); // 新的文件名 string newfilename = this.getname(filename); // 文件扩展名 string fileend = this.getfileext(filename); // 绝对路径 string 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(); } // 相对路径 entity.settype(fileend); string filedir = logopathdir + newfilename + fileend; stringbuilder builder = new stringbuilder(filedir); string finalfiledir = builder.substring(1); // size存储为string string size = this.getsize(filedirs); // 源文件保存路径 string avipath = filedirs.getabsolutepath(); // 转码avi // boolean flag = false; if (this.checkavitype(fileend)) { // 设置转换为avi格式后文件的保存路径 string codcavipath = logorealpathdir + file.separator + newfilename + ".avi"; // 获取配置的转换工具(mencoder.exe)的存放路径 string mencoderpath = 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格式后文件的保存路径 string codcfilepath = logorealpathdir + file.separator + newfilename + ".flv"; // 获取配置的转换工具(ffmpeg.exe)的存放路径 string ffmpegpath = request.getsession().getservletcontext().getrealpath("/tools/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); timestamp timestamp = new timestamp(system.currenttimemillis()); entity.setuploadtime(timestamp); return entity; } 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; } } return false; } /** * 视频类型判断(flv) * * @param filename * @return */ private boolean checkmediatype(string fileend) { iterator<string> type = arrays.aslist(allowflv).iterator(); while (type.hasnext()) { string ext = type.next(); if (fileend.equals(ext)) { return true; } } return false; } /** * 视频类型判断(avi) * * @param filename * @return */ private boolean checkavitype(string fileend) { iterator<string> type = arrays.aslist(allowavi).iterator(); while (type.hasnext()) { string ext = type.next(); if (fileend.equals(ext)) { return true; } } return false; } /** * 获取文件扩展名 * * @return string */ private string getfileext(string filename) { return filename.substring(filename.lastindexof(".")); } /** * 依据原始文件名生成新文件名 * @return */ private string getname(string filename) { iterator<string> type = arrays.aslist(allowfiles).iterator(); while (type.hasnext()) { string ext = type.next(); if (filename.contains(ext)) { string newfilename = filename.substring(0, filename.lastindexof(ext)); return newfilename; } } return ""; } /** * 文件大小,返回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 * * @param ffmpegpath * 转码工具的存放路径 * @param upfilepath * 用于指定要转换格式的文件,要截图的视频源文件 * @param codcfilepath * 格式转换后的的文件保存路径 * @return * @throws exception */ public void processflv(string ffmpegpath, string upfilepath, string codcfilepath) { // 创建一个list集合来保存转换视频文件为flv格式的命令 list<string> 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 (interruptedexception e) { e.printstacktrace(); } } /** * 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等), 先用mencoder转换为avi(ffmpeg能解析的)格式 * * @param mencoderpath * 转码工具的存放路径 * @param upfilepath * 用于指定要转换格式的文件,要截图的视频源文件 * @param codcfilepath * 格式转换后的的文件保存路径 * @return * @throws exception */ public string processavi(string 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 { // 预处理进程 processbuilder builder = new processbuilder(); builder.command(commend); builder.redirecterrorstream(true); // 进程信息输出到控制台 process p = builder.start(); bufferedreader br = new bufferedreader(new inputstreamreader(p.getinputstream())); string line = null; while ((line = br.readline()) != null) { system.out.println(line); } p.waitfor();// 直到上面的命令执行完,才向下执行 return codcavipath; } catch (exception e) { e.printstacktrace(); return 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); else break; } } catch (exception e) { e.printstacktrace(); } } }
实体类
import java.sql.timestamp; public class fileentity { private string type; private string size; private string path; private string titleorig; private string titlealter; private timestamp uploadtime; 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 titleorig; } 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上传视频实例代码,希望对大家有所帮助