Java uploads video instance code

  • 2020-12-19 21:01:05
  • OfStack

Page:

Keywords: enctype="multipart/ ES5en-ES6en"


<%@ 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> Upload video </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"> File upload </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"> File upload 
            <input type="file" class="form-control" name="file" id="file"><br>
            <input type="submit" value=" upload ">
          </div>
        </div>
      </form>
    </div>
  </div>
</body>
</html>

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;
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 = " 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);
  }
}

Utility class


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();
  //  file 500M
  private static long upload_maxsize = 800 * 1024 * 1024;
  //  File allowed format 
  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" };
  //  Transcoding allowed video format ( ffmpeg ) 
  private static String[] allowFLV = { ".avi", ".mpg", ".wmv", ".3gp",
      ".mov", ".asf", ".asx", ".vob" };
  //  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();
    //  Verify that the file is not empty 
    if (multipartFile.getSize() != 0 && !multipartFile.isEmpty()) {
      bflag = true;
      //  Determine file size 
      if (multipartFile.getSize() <= upload_maxsize) {
        bflag = true;
        //  File type determination 
        if (this.checkFileType(fileName)) {
          bflag = true;
        } else {
          bflag = false;
          System.out.println(" File types are not allowed ");
        }
      } else {
        bflag = false;
        System.out.println(" File size beyond range ");
      }
    } else {
      bflag = false;
      System.out.println(" The file is empty ");
    }
    if (bflag) {
      String logoPathDir = "/video/";
      String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);
      //  Upload to 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 filename 
      String newFileName = this.getName(fileName);
      //  File extension 
      String fileEnd = this.getFileExt(fileName);
      //  An absolute path 
      String fileNamedirs = logoRealPathDir + File.separator + newFileName + fileEnd;
      System.out.println(" Absolute path saved: " + fileNamedirs);
      File filedirs = new File(fileNamedirs);
      //  Into the file 
      try {
        multipartFile.transferTo(filedirs);
      } catch (IllegalStateException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      //  Relative paths 
      entity.setType(fileEnd);
      String fileDir = logoPathDir + newFileName + fileEnd;
      StringBuilder builder = new StringBuilder(fileDir);
      String finalFileDir = builder.substring(1);
      // size Stored as String
      String size = this.getSize(filedirs);
      //  The source file saves the path 
      String aviPath = filedirs.getAbsolutePath();
      //  transcoding Avi
//      boolean flag = false;
      if (this.checkAVIType(fileEnd)) {
        //  Set convert to AVI The save path for the file after formatting 
        String codcAviPath = logoRealPathDir + File.separator + newFileName + ".avi";
        //  Get the configured transformation tool ( 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) {
        //  transcoding Flv
        if (this.checkMediaType(fileEnd)) {
          try {
            //  Set convert to flv The save path for the file after formatting 
            String codcFilePath = logoRealPathDir + File.separator + newFileName + ".flv";
            //  Get the configured transformation tool ( 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;
    }
  }
  /**
   *  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> type = 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;
  }
  /**
   *  Gets the file extension 
   *
   * @return string
   */
  private String getFileExt(String fileName) {
    return fileName.substring(fileName.lastIndexOf("."));
  }
  /**
   *  Generate a new file name based on the original 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 = fileName.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
   *       The path to the transcoding tool 
   * @param upFilePath
   *       Used to specify the file format to convert , To capture the video source file 
   * @param codcFilePath
   *       Format converted file save path 
   * @return
   * @throws Exception
   */
  public void processFLV(String ffmpegPath, String upFilePath, String codcFilePath) {
    //  create 1 a List Collection to save the converted video file for flv Formatted command 
    List<String> convert = new ArrayList<String>();
    convert.add(ffmpegPath); //  Add the transformation tool path 
    convert.add("-i"); //  Add parameter "" -i ", which specifies the file to convert 
    convert.add(upFilePath); //  Add the path to the video file you want to convert 
    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"); //  Specifies the quality of the transformation  convert.add("6");
     * convert.add("-ab"); //  Set the audio bit rate  convert.add("64"); convert.add("-ac");
     * //  Set the number of channels  convert.add("2"); convert.add("-ar"); //  Set the sampling frequency of the sound 
     * convert.add("22050"); convert.add("-r"); // 设置帧频 convert.add("24");
     * convert.add("-y"); //  Add parameter "" -y ", which specifies that existing files 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();
    }
  }
  /**
   *  right ffmpeg Unparsable file format (wmv9 . rm . rmvb Etc. ),  Use first mencoder convert avi(ffmpeg Can parse ) format 
   *
   * @param mencoderPath
   *       The path to the transcoding tool 
   * @param upFilePath
   *       Used to specify the file format to convert , To capture the video source file 
   * @param codcFilePath
   *       Format converted file save path 
   * @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 {
      //  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();//  It does not run down until the above command is finished 
      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();
    }
  }
}

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

conclusion


Related articles: