Java video upload instance code, java upload instance

Source: Internet
Author: User

Java video upload instance code, java upload instance

Page:

Keyword during file upload: 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"> 

Background:

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; I Mport 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 req Uest, 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 = "uploaded successfully"; map. put ("entity", entity); map. put ("result", message);} else {message = "Upload Failed"; map. put ("result", message) ;}} catch (Exception e) {e. printStackTrace ();} return new ModelAndView ("result", map );}}

Tool

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 (); // maximum file size: 500 mb private static long uplo Ad_maxsize = 800*1024*1024; // the file format is 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 "}; // The video format (ffmpeg) private static String [] allowFLV = {". avi ",". mpg ",". wmv ",". 3gp ", ". Mov ",". asf ",". asx ",". vob "}; // The allowed video transcoding format (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 (); // judge whether the file is not empty if (multipartFile. getSize ()! = 0 &&! MultipartFile. isEmpty () {bflag = true; // determine the file size if (multipartFile. getSize () <= upload_maxsize) {bflag = true; // determine if (this. checkFileType (fileName) {bflag = true;} else {bflag = false; System. out. println ("file type not allowed") ;}} else {bflag = false; System. out. println ("file size out of range") ;}} else {bflag = false; System. out. println ("file is empty");} if (bflag) {String logoPathDir = "/video/"; String logoRea LPathDir = request. getSession (). getServletContext (). getRealPath (logoPathDir); // upload to a local disk // String logoRealPathDir = "E:/upload"; File logoSaveFile = new File (logoRealPathDir); if (! LogoSaveFile. exists () {logoSaveFile. mkdirs ();} String name = fileName. substring (0, fileName. lastIndexOf (". "); System. out. println ("file name:" + name); // new file name String newFileName = this. getName (fileName); // file extension String fileEnd = this. getFileExt (fileName); // absolute path String fileNamedirs = logoRealPathDir + File. separator + newFileName + fileEnd; System. out. println ("absolute path:" + fileNamedirs); File file Dirs = new File (fileNamedirs); // Transfer File try {multipartFile. transferTo (filedirs);} catch (IllegalStateException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} // relative path entity. setType (fileEnd); String fileDir = logoPathDir + newFileName + fileEnd; StringBuilder builder = new StringBuilder (fileDir); String finalFileDir = builder. substring (1); // size is stored as String size = This. getSize (filedirs); // source file storage path String aviPath = filedirs. getAbsolutePath (); // transcode Avi // boolean flag = false; if (this. checkAVIType (fileEnd) {// set the Save path of the File after conversion to AVI format: String codcAviPath = logoRealPathDir + File. separator + newFileName + ". avi "; // storage path of the configured Conversion Tool (mencoder.exe) String mencoderPath = request. getSession (). getServletContext (). getRealPath ("/tools/mencoder.exe"); aviPath = transfMedia Tool. processAVI (mencoderPath, filedirs. getAbsolutePath (), codcAviPath); fileEnd = this. getFileExt (codcAviPath);} if (aviPath! = Null) {// transcode Flv if (this. checkMediaType (fileEnd) {try {// set the storage path of the File to flv after conversion. String codcFilePath = logoRealPathDir + File. separator + newFileName + ". flv "; // storage path of the configured Conversion Tool (ffmpeg.exe) String ffmpegPath = request. getSession (). getServletContext (). getRealPath ("/tools/ffmpeg.exe"); transfMediaTool. processFLV (ffmpegPath, aviPath, codcFilePath); fileDir = logoPathDir + newFileName + ". flv "; build Er = 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 ;}}/** * File type determination ** @ 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;}/*** video type judgment (flv) ** @ param fileName * @ return */private boolean checkMediaType (String fileEnd) {Iterator <String> ty Pe = Arrays. asList (allowFLV ). iterator (); while (type. hasNext () {String ext = type. next (); if (fileEnd. equals (ext) {return true ;}} return false ;}/ *** video type judgment (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;}/*** get file extension ** @ return string */private String getFileExt (String fileName) {return fileName. substring (fileName. lastIndexOf (". ");}/*** generate a new file name * @ 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 = fil EName. substring (0, fileName. lastIndexOf (ext); return newFileName;} return ";}/*** file size, 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 {/*** Video Transcoding flv ** @ param ffmpegPath * Transcoder * @ Param upFilePath * is used to specify the file to be converted, the file storage path after the video source file * @ param codcFilePath * format conversion * @ return * @ throws Exception */public void processFLV (String ffmpegPath, String upFilePath, String codcFilePath) {// create a List set to save the command List <String> convert = new ArrayList <String> (); convert. add (ffmpegPath); // add the Conversion Tool Path convert. add ("-I"); // add the parameter "-I", which specifies the file to be converted to convert. add (upFilePath); // add the format to be converted The path of the video file 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"); // specify the conversion quality convert. add ("6"); * convert. add ("-AB"); // sets the audio bit rate convert. add ("64"); convert. add ("-ac"); * // sets the number of audio channels convert. add ("2"); convert. add ("-ar"); // sets the audio sampling frequency. * Convert. add ("22050"); convert. add ("-r"); // sets the frame rate convert. add ("24"); * convert. add ("-y"); // add the parameter "-y", which specifies that the existing file will be overwritten */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 () ;}}/*** for file formats that cannot be parsed by ffmpeg (wmv9, rm, rmvb, etc.), use mencoder to convert to avi (which can be parsed by ffmpeg) format ** @ param mencoderPath * storage path of the transcoding tool * @ param upFilePath * is used to specify the file to be converted, the file storage path after the video source file * @ param codcFilePath * format conversion * @ return * @ throws Exception */public String processAVI (String mencoderPath, String upFilePath, String codcAviPath) {// boolean flag = false; List <String> commend = new ArrayList <St Ring> (); 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 (codcAvi Path); try {// preprocessing process ProcessBuilder builder = new ProcessBuilder (); builder. command (commend); builder. redirectErrorStream (true); // Process information is output to the console 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 (); // do not run return codcAviPath until the preceding command is executed;} 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 ();}}}

Entity class

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;  }}

Summary

The above is the Java upload video instance Code introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.