:
上传文件时的关键词: ENCTYPE = "Multipart / Form-Data"
<% @ page langage = "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> rel = "external nofollow"> <ititle> 上传视频 </title> <meta http-equiv = "pragma" contenu = "non-cache"> <meta http-equiv = "cache-control" contenu = "non-cache"> <méta http-equiv = "expires" contenu = "0"> <méta http-equiv = " content = "Keyword1, Keyword2, Keyword3"> <meta http-equiv = "description" contenu = "Ceci est ma page"> </ head> <body> <div> <div> <div align = "Center"> <h1> 文件上传 </h1> </div> <hr> <form id = "upload" method = "post" action = "uploadflv / upload.do" ENCTYPE = "Multipart / Form-data"> <div align = "Center"> <div> 文件上传 <input type = "file" name = "file" id = "file"> <br> <input type = "soumi" value = "上传"> </div> </div> </ form> </ div> </div> </ body> </html>
:
contrôleur
import javax.servlet.http.httpservletRequest; import Model.Fileentity; import org.springframework.sterreotype.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; org.springframework.web.servlet.modelandView; @ contrôleur @ requestmapping ("/ uploadflv") public class uploadController {@RequestMapping (value = "/ upload", méthode = {requestMethod.post, requestMethod.get}) @ResponseBody Public ModelView upload (@requestParam (value = "File MultipartFile, HttpServLetRequest Request, ModelMap Map) {String Message = ""; FileEntity Entity = new FileEntity (); FileUploadTool fileuploadTool = new FileUploadTool (); essayez {entity = fileuploadTool.CreateFile (multipartFile, demande); if (entité! = null) {// Service.SaveFile (entité); message = "上传成功"; map.put ("entité", entité); map.put ("résultat", message); } else {message = "上传失败"; map.put ("résultat", 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.array org.springframework.web.multiparpart.multupartfile; public class fileuploadTool {transfmediatool transfmediatool = new TransfMediAtool (); // 文件最大 500m STATIQUE PRIVÉ Long Upload_maxsize = 800 * 1024 * 1024; // 文件允许格式 String statique privé [] AllowFiles = {".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".xlsx", ".gif", ".png", ".jpg", ".jpeg", ".bmp", ". ".flv", ".ppt", ".avi", ".mpg", ".wmv", ".3gp", ".mov", ".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb"}; // 允许转码的视频格式 (ffmpeg) chaîne statique privée [] allowflv = {".avi", ".mpg", ".wmv", ".3gp", ".mov", ".asf", ".asx", ".vob"}; // 允许的视频转码格式 (Mencoder) String statique privé [] allowavi = {".wmv9", ".rm", ".rmvb"}; Public FileEntity CreateFile (multipartFile MultipartFile, HttpServLetRequest Request) {FileEntity Entity = new FileEntity (); booléen 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 (nom de fichier)) {bflag = true; } else {bflag = false; System.out.println ("文件类型不允许"); }} else {bflag = false; System.out.println ("文件大小超范围"); }} else {bflag = false; System.out.println ("文件为空"); } if (bflag) {String logopathdir = "/ vidéo /"; String logorealPathDir = request.getSession (). GetServletContext (). GetRealPath (logopathdir); // 上传到本地磁盘 // String logorealpathdir = "e: / upload"; Fichier logoSaveFile = nouveau fichier (logorealPathDir); if (! logosavefile.exists ()) {logosavefile.mkDirs (); } String name = filename.substring (0, filename.lastIndexof (".")); System.out.println ("文件名称:" + nom); // 新的文件名 String newFileName = this.getName (nom de fichier); // 文件扩展名 String FileEnd = this.getFileExt (nom de fichier); // 绝对路径 String filenameDirs = logorealpathdir + file.separator + newFileName + fileend; System.out.println ("保存的绝对路径 :" + filenameDirs); Fichier filedIRS = nouveau fichier (filenamedirs); // 转入文件 essayez {multipartFile.transferto (fileDirs); } catch (illégalStateException 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); // Taille 存储为 String String size = this.getSize (fileDIRS); // 源文件保存路径 String Avipath = fileDirs.getAbsolutepath (); // 转码 avi // booléen drapeau = 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 (taille); entity.setPath (finalfiledir); entity.setTitleORIG (name); entity.setTitlealter (newFileName); Timestamp Timestamp = Nouveau horodatage (System.CurrentTimeMillis ()); Entity.SetUploadTime (horodat); entité de retour; } 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)); retourner newFileName; } } retour ""; } / ** * 文件大小 , 返回 kb.mb * * @return * / private String getSize (fichier file) {String size = ""; long fileLength = file.length (); Decimalformat df = new Decimalformat ("#. 00"); if (fileLength <1024) {size = df.format ((double) fileLelength) + "bt"; } else if (fileLength <1048576) {size = df.format ((double) fileLelength / 1024) + "kb"; } else if (fileLength <1073741824) {size = df.format ((double) fileLength / 1048576) + "MB"; } else {size = df.format ((double) fileLength / 1073741824) + "gb"; } taille de retour; }}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 (); } E MencoderPath, String upFilePath, String codcavipath) {// boolean flag = false; List <string> ward = new ArrayList <string> (); SEDL.ADD (MENCODERPATH); wend.add (upfilepath); wend.add ("- oac"); alorsnd.add ("mp3lame"); SEDRAND.ADD ("- LAMEOPTS"); wend.add ("préset = 64"); wend.add ("- lavcopts"); wend.add ("acdec = mp3: abitrate = 64"); wed.add ("- ovc"); wend.add ("xvid"); SEDRAND.ADD ("- XVIDENCOPTS"); wend.add ("bitrate = 600"); SEDL.ADD ("- OF"); wend.add ("avi"); SEDRAND.ADD ("- O"); wend.add (Codcavipath); essayez {// 预处理进程 processBuilder builder = new ProcessBuilder (); builder.command (félicitation); builder.redireCterRorstream (true); // 进程信息输出到控制台 processus p = builder.start (); BufferedReader br = new BufferedReader (new inputStreamReader (p.getInputStream ())); Chaîne line = null; while ((line = br.readline ())! = null) {System.out.println (line); } P.WaitFor (); // 直到上面的命令执行完 , 才向下执行 RETOUR CODCAVIPATH; } catch (exception e) {e.printStackTrace (); retourner null; }}} classe PrintStream étend 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); d'autre se casse; }} catch (exception e) {e.printStackTrace (); }}}实体类
import java.sql.timestamp; public class fileentity {private String Type; taille de chaîne privée; Path de chaîne privé; String Private Titleorig; Titlealter de chaîne privée; Tobinage privé Téléchargement de temps; 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 SetttLeorIg (String titleorig) {this.titleorig = titleorig; } public String getTitlealter () {return titLealter; } public void SetttLealter (String titlealter) {this.titlealter = titlealter; } public horodatamp getUploadTime () {return uploadTime; } public void setuploadTime (horodatage uploadtime) {this.uploadtime = uploadTime; }}总结
以上所述是小编给大家介绍的 Java 上传视频实例代码 , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!