页面
上传文件时的关键词 : Enctype = "Multipart/Form-Data"
<%@ página de página = "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 = "Nofollow externo"> <Title> 上传视频 </ititle> <meta http-equiv = "PRAGMA" content = "no-cache"> <meta http-equiv = "cache-controle" content = "no-cache"> <meta http-equiv = "expires" = "0"> <meta " Content = "Palavra-chave1, palavra-chave2, palavra-chave3"> <meta http-equiv = "description" content = "esta é minha página"> </ad Head> <body> <div> <div> <div align = "central"> <h1> 文件上传 </h1> </div> <hr> <fort id = "uplarload" Method) "Post) Enctype = "Multipart/form-Data"> <div align = "Center"> <div> 文件上传 <input type = "file" name = "file" id = "file"> <br> <input type = "submit" value = "上传"> </div> </div> </form> </div> </div = </body "
后台
controlador
importar javax.servlet.http.httpServletRequest; importar model.FileEntity; importar org.springframework.tereotype.controller; importar org.springframework.ui.modelmap; importar org.springframework.web.bind.anotation.rentation; org.springframework.web.bind.annotation.requestmethod; importar org.springframework.web.bind.annotation.requestparam; importar org.springframework.web.bind.annotation.ResponsoBody; importação.springfringfringfringfringFringFringFringFringFringFringFringFring.web.web.Bind.annotation.Responsoody; org.springframework.web.servlet.modlandView;@controlador@requestmapping ("/uploadflv") public MultipartFile, httpServletRequest solicitação, mapa de modelMap) {string message = ""; FileEntity entity = new FileEntity (); FileUploadTool fileUploadTool = new FileUploadTool (); tente {entity = fileUploadTool.createfile (multipartfile, solicitação); if (entidade! = null) {// service.savefile (entidade); message = "上传成功"; map.put ("entidade", entidade); map.put ("resultado", mensagem); } else {message = "上传失败"; map.put ("resultado", mensagem); }} catch (Exceção e) {e.printStackTrace (); } retornar new ModelAndView ("Resultado", mapa); }}工具类
importar java.io.file; importar java.io.ioException; importar java.sql.timestamp; importar java.text.decimalformat; importar java.util.arrays; importar java.util.iterator; importráx. org.springframework.web.multipart.multipartFile; public class FileUploadTool {TransfMediATool TransfMediatool = new TransfMediATool (); // 文件最大 500M private estático 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 terce String estática privada [] allowflv = {".avi", ".mpg", ".wmv", ".3gp", ".Mov", ".asf", "sx "," .Vob "}; // 允许的视频转码格式 (mencoder) String estática privada [] allowavi = {".wmv9", ".rm", ".rmvb"}; FileEntidade pública createfile (multipart -multipart arquivo, httpServletRequest Solicy) {FileEntity entity = new FileEntity (); booleano 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 (nome do arquivo)) {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"; Arquivo logosavefile = novo arquivo (logoreAlPathdir); if (! LOGOSAVEFILE.EXISTS ()) {LOGOSAVEFILE.MKDIRS (); } String name = filename.substring (0, filename.lastindexof (".")); System.out.println ("文件名称 ::" + nome); // 新的文件名 string newFilename = this.getName (nome do arquivo); // 文件扩展名 string fileEnd = this.getFileExt (nome do arquivo); // 绝对路径 String filenamedirs = LogoreAlPathdir + file.separator + newFileName + FileEnD; System.out.println ("保存的绝对路径 ::" + filenamedirs); Arquivo filedirs = novo arquivo (filenamedirs); // 转入文件 tente {multipartFile.Transferto (Filedirs); } catch (ilegalStateException 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); // tamanho 存储为 string string size = this.getSize (Filedirs); // 源文件保存路径 string avipath = filedirs.getabsolutepath (); // 转码 Avi // sinalizador booleano = false; if (this.checkavitype (fileEND)) {// 设置转换为 Avi 格式后文件的保存路径 String codCavipath = LogoreAlPathdir + file.separator + newFileName + ".avi"; // 获取配置的转换工具 (mencoder.exe) 的存放路径 string mencoderPath = request.getSession (). GetServletContext (). GetRealPath ("/ferramentas/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 = logoreAlathdir + file.separator + newFileName + ".flv"; // 获取配置的转换工具 (ffmpeg.exe) 的存放路径 string ffmpegpath = request.getSession (). GetServletContext (). GetRealPath ("/ferramentas/ffmpeg.exe"); transfmediatool.processflv (ffmpegpath, avipatath, codcfilepath); filedir = logopathdir + newFileName + ".flv"; construtor = new StringBuilder (Filedir); finalFiledir = Builder.Substring (1); } catch (Exceção e) {e.printStackTrace (); }} entity.SetSize (tamanho); entity.setPath (Finalfiledir); entity.setTitleorig (nome); entity.setTitLealter (newFileName); Timestamp Timestamp = novo Timestamp (System.CurrentTimemillis ()); entity.setUploadTime (Timestamp); entidade de retorno; } 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; }} retornar false; } / ** * 视频类型判断 (flv) * * @param filename * @return * / private boolean checkMediType (string fileEND) {iterator <string> type = Arrays.asList (allowflv) .Iterator (); while (type.hasNext ()) {string ext = type.Next (); if (fileEND.equals (ext)) {return true; }} retornar false; } / ** * 视频类型判断 (AVI) * * @param filename * @return * / private boolean checkavitype (string fileEND) {iterator <string> type = Arrays.asList (allowAavi) .iterator (); while (type.hasNext ()) {string ext = type.Next (); if (fileEND.equals (ext)) {return true; }} retornar 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)); retornar newfileName; } } retornar ""; } / ** * 文件大小 , 返回 KB.MB * * @return * / String privada GetSize (arquivo de arquivo) {string size = ""; long fileLength = file.length (); Decimalformat df = novo decimalformat ("#. 00"); if (comprimento do arquivo <1024) {size = df.format ((duplo) comprimento do arquivo) + "bt"; } else if (filelelenth <1048576) {size = df.format (((duplo) comprimento / 1024) + "kb"; } else if (FileLength <1073741824) {size = df.format ((duplo) comprimento do arquivo / 1048576) + "mb"; } else {size = df.format ((duplo) fileLength / 1073741824) + "gb"; } tamanho de retorno; }} importar java.io.bufferedReader; importar java.io.ioException; importar java.io.inputStreamReader; importar java.util.arraylist; importar java.util.list; classe pública transfmediAtool { /** ** * 视频转码 fffmpathpath * 转码工具的存放路径 @** ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * codcfilepath * 格式转换后的的文件保存路径 * @return * @throws Exception */ public void processflv (string ffmpegPath, string upFilePath, string codcFilePath) {// 创建一个 list 集合来保存转换视频文件为 flv 格式的命令 list <tring> 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); tente {Process videoprocess = new ProcessBuilder (convert) .RedirecterRorStream (true) .start (); novo 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 upfilePhath * 用于指定要转换格式的文件, @param * mencoderpath, string upFilePath, string codcavipath) {// sinalizador booleano = false; List <String> elogio = new ArrayList <String> (); elogio.add (mencoderpath); elogio.add (upFilePath); elogio.add ("-oac"); elogio.add ("mp3Lame"); elogio.add ("-lameopts"); elogio.add ("predefinição = 64"); elogio.add ("-lavcopts"); elogio.add ("acodec = mp3: abitrato = 64"); elogio.add ("-OVC"); elogio.add ("xvid"); elogio.add ("-xvidenchopts"); elogio.add ("Taxa de bits = 600"); elogio.add ("-de"); elogio.add ("Avi"); elogio.add ("-o"); elogio.add (codcavipath); tente {// 预处理进程 ProcessBuilder Builder = new ProcessBuilder (); construtor.Command (elogio); builder.redirecterRorStream (true); // 进程信息输出到控制台 Process p = builder.start (); BufferErader BR = new BufferredReader (novo InputStreamReader (p.getInputStream ())); Linha de string = null; while ((line = Br.readline ())! = null) {System.out.println (line); } P.Waitfor (); // 直到上面的命令执行完 , 才向下执行 Return codcavipath; } catch (Exceção e) {e.printStackTrace (); retornar nulo; }}} classe PrintStream estende o 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); mais quebrar; }} catch (Exceção e) {e.printStackTrace (); }}}实体类
importar java.sql.timestamp; public class FileEntity {private string tipo; Tamanho do String Private; Caminho de cordas privadas; String private Titleorig; String private Titlealter; tempo de upload de registro de registro privado; public String getType () {return type; } public void setType (string type) {this.type = type; } public string getSize () {return size; } public void SetSize (tamanho da string) {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 上传视频实例代码 , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!