页面 :
上传文件时的关键词 : enctype = "multipart/form-data"
<%@ halaman bahasa = "java" import = "java.util.*" pageEncoding = "UTF-8"%> <%string path = request.getContextPath (); String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerport ()+path+"/";%> <! Doctype html publik "-//" DTD = BASEF = BASEF/BASEF/BASEF/BASEF/BASEF/BASEF/BASEF/BASEF/BASEF/BASEF =%HTERPERNAL/BOAD =%HTEFLIONAL/BASEF =%HTEFL <%HTEFL <%HTEFL <%HTEF/BASEF/EERP EONSISTAS 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> <vet> <Div align = "center"> <h1> 文件上传 </h1> </div> <hr> <bentuk id = "unggah" Method = "Method =" Method = "Method =" Method = "Method =" Method = "Method =" Method = "Method =" Method = "Method =" Method = "Method =" Method = "Method =" Method = "Method =" Method = "Method =" Method = "Method =" Method = "Method =" enctype = "multipart/form-data"> <div align = "center"> <verv> 文件上传 <input type = "file" name = "file" id = "file"> <br> <input type = "kirim" value = "上传"> </div> </div> </form> </divit </div> </body> </htm
后台 :
pengontrol
Impor javax.servlet.http.httpservletrequest; model impor.fileentity; impor org.springframework.stereotype.controller; impor org.springframework.ui.modelmap; impor org.springframework.web.bind.annotation.rupaping org.springframework.web.bind.annotation.requestmethod; impor org.springframework.web.bind.annotation.requestparam; impor org.springframework.web.bind.annotation.responseBody; impor org.springframework.wub.win 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, permintaan httpservletRequest, peta modelmap) {string message = ""; FileEntity Entity = new FileEntity (); FileuploadTool fileuploadtool = FileuploadTool baru (); coba {entitas = fileuploadtool.createFile (multipartfile, request); if (entitas! = null) {// service.savefile (entitas); pesan = "上传成功"; peta.put ("entitas", entitas); peta.put ("hasil", pesan); } else {message = "上传失败"; peta.put ("hasil", pesan); }} catch (Exception e) {e.printstacktrace (); } return new ModelandView ("hasil", peta); }}工具类
impor java.io.file; impor java.io.ioException; impor java.sql.timestamp; impor java.text.decimalformat; import java.util.arrays; import java.util.iterator; import javax.servlet.http.htpservlet; org.springframework.web.multipart.multipartfile; Fileuploadtool kelas publik {transfMediatool transfMediatool = new transfmediatool (); // 文件最大 500m private static long unggah_maxsize = 800 * 1024 * 1024; // 文件允许格式 string statis pribadi [] Allowfiles = {".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".xlsx", ".gif", ".png", ".jpg", ".pegeg", ".png", ".jpg", ".pnpeg", ".png". ".flv", ".ppt", ".avi", ".mpg", ".wmv", ".3gp", ".mov", ".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb"}; // 允许转码的视频格式( ffmpeg) string statis pribadi [] allowflv = {".avi", ".mpg", ".wmv", ".3gp", ".mov", ".asf", ".asx", ".vob"}; // 允许的视频转码格式 (Mencoder) string statis pribadi [] izinvi = {".wmv9", ".rm", ".rmvb"}; Public FileEntity CreateFile (MultipartFile MultipartFile, permintaan httpservletRequest) {FileEntity Entity = new FileEntity (); boolean bflag = false; String filename = multipartfile.getoriginalfileName (). ToString (); // 判断文件不为空 if (multipartfile.getsize ()! = 0 &&! MultipartFile.isempty ()) {bflag = true; // 判断文件大小 if (multipartfile.getsize () <= unggah_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 LogOeAlPathDir = request.getSession (). GetServletContext (). GetRealPath (LogopathDir); // 上传到本地磁盘 // String LogoreAlPathDir = "E:/Unggah"; File logoSaveFile = file baru (logorealpathdir); if (! LOGOSAVEFILE.exists ()) {LOGOSAVEFILE.MKDIRS (); } String name = filename.substring (0, filename.LastIndexof (".")); System.out.println ("文件名称 :" + Nama); // 新的文件名 String newFileName = this.getName (fileName); // 文件扩展名 string fileEnd = this.getFileExt (fileName); // 绝对路径 string fileNamedIrs = logeorealpathdir + file.separator + newFileName + fileEnd; System.out.println ("保存的绝对路径 :" + FileNamedirs); File FileDirs = File baru (FileNamedIRS); // 转入文件 coba {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); // 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"; // 获取配置的转换工具( mesencoder.exe )的存放路径 string mesencoderpath = request.getSession (). GetServletContext (). GetRealPath ("/tools/prencoder.exe"); avipath = transfmediatool.processavi (Mencoderpath, filedirs.getabsolutePath (), codcavipath); fileEnd = this.getFileExt (codCavIpath); } if (avipath! = null) {// 转码 flv if (this.checkMediatype (fileEnd)) {coba {// 设置转换为 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 (nama); entity.settitlealter (newFileName); Timestamp waktu = stempel waktu baru (System.currentTimeMillis ()); entity.setuploadtime (timestamp); entitas kembali; } 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 (ijinvi) .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)); mengembalikan nama baru; } } kembali ""; } / ** * 文件大小 , 返回 kb.mb * * @return * / string private 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"; } ukuran pengembalian; }} import java.io.bufferedReader; import java.io.ioexception; import java.io.inputStreamreader; impor java.util.arraylist; import java.util.list; public class transfmediatool { /** * 视频转码 flv * * @param ffm * public { /** * 视频转码 flv * * @param ffmp ffmp @param codcfilePath * 格式转换后的的文件保存路径 * @return * @throws Exception */ public void ProcessFlv (String ffMPegPath, String upFilePath, String codcfilePath) {// 创建一个 Daftar 集合来保存转换视频文件为 flv 格式的命令 Daftar <String> convert = ArrayList baru <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); coba {Process videoprocess = new ProcessBuilder (Convert) .redIrecterrorStream (true) .start (); printStream baru (videoprocess.getInputStream ()). start (); videoprocess.waitfor (); } catch (ioException e1) {e1.printstacktrace (); } catch (InterruptedException e) {E.PrintStackTrace (); }} / ** * 对 ffmpEG 无法解析的文件格式 (wmv9 , rm , rmvb 等), 先用 Mencoder 转换为 avi (ffmpeg 能解析的) 格式 * * @param menoderpath * 转码工具的存放路径 * @param upfilepath * 用于指定要转换格式的文件, 要截图的视频源文件 @param @param codcfilepath * MencoderPath, string upfilePath, string codcavipath) {// boolean flag = false; Daftar <String> comend = new ArrayList <String> (); commend.add (Mencoderpath); commend.add (upfilePath); commend.add ("-oac"); comend.add ("mp3lame"); commend.add ("-lameopts"); commend.add ("preset = 64"); commend.add ("-lavcopts"); comen.add ("acodec = mp3: abitrate = 64"); commend.add ("-ovc"); commend.add ("xvid"); commend.add ("-xvidencopts"); comen.add ("Bitrate = 600"); commend.add ("-of"); commend.add ("avi"); commend.add ("-o"); commend.add (codcavipath); coba {// 预处理进程 processBuilder builder = new ProcessBuilder (); builder.command (comend); builder.redirecterrorstream (true); // 进程信息输出到控制台 Proses p = builder.start (); BufferedReader BR = BufferedReader baru (inputStreamReader baru (p.getInputStream ())); Garis string = null; while ((line = br.readline ())! = null) {System.out.println (line); } p.waitfor (); // 直到上面的命令执行完 , 才向下执行 return codcavipath; } catch (Exception e) {E.PrintStackTrace (); kembali nol; }}} kelas printStream memperluas utas {java.io.inputStream __is = null; Public printStream (java.io.inputStream adalah) {__is = is; } public void run () {coba {while (this! = null) {int _ch = __is.read (); if (_ch! = -1) system.out.print ((char) _ch); Lainnya istirahat; }} catch (Exception e) {e.printstacktrace (); }}}实体类
impor java.sql.timestamp; FileEntity kelas publik {private string type; ukuran string pribadi; jalur string pribadi; Private String Titleorig; Private String Titlealter; waktu pengunggahan waktu pribadi; string publik getType () {type return; } 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; } waktu publik getUploadTime () {return unggahan waktu; } public void setuploadtime (timestamp unggahtime) {this.uploadtime = unggah waktu; }}总结
以上所述是小编给大家介绍的 Java 上传视频实例代码 , 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!