欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java上傳視頻實(shí)例代碼

 更新時(shí)間:2018年01月10日 09:14:43   作者:smart_hwt  
本文通過實(shí)例代碼給大家講解了java上傳視頻功能,代碼分為頁面前臺和后臺,工具類,具體實(shí)例代碼大家通過本文學(xué)習(xí)吧

頁面:

上傳文件時(shí)的關(guān)鍵詞: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">
<html>
<head>
  <base href="<%=basePath%>" rel="external 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 class="panel panel-default">
    <div class="panel-body">
      <div class="panel-heading" align="center"><h1 class="sub-header h3">文件上傳</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">文件上傳
            <input type="file" class="form-control" name="file" id="file"><br>
            <input type="submit" value="上傳">
          </div>
        </div>
      </form>
    </div>
  </div>
</body>
</html>

后臺:

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 = "上傳成功";
        map.put("entity", entity);
        map.put("result", message);
      } else {
        message = "上傳失敗";
        map.put("result", 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.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();
  // 文件最大500M
  private static 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" };
  // 允許轉(zhuǎn)碼的視頻格式(ffmpeg)
  private static String[] allowFLV = { ".avi", ".mpg", ".wmv", ".3gp",
      ".mov", ".asf", ".asx", ".vob" };
  // 允許的視頻轉(zhuǎn)碼格式(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();
    // 判斷文件不為空
    if (multipartFile.getSize() != 0 && !multipartFile.isEmpty()) {
      bflag = true;
      // 判斷文件大小
      if (multipartFile.getSize() <= upload_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 logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);
      // 上傳到本地磁盤
      // String logoRealPathDir = "E:/upload";
      File logoSaveFile = new File(logoRealPathDir);
      if (!logoSaveFile.exists()) {
        logoSaveFile.mkdirs();
      }
      String name = fileName.substring(0, fileName.lastIndexOf("."));
      System.out.println("文件名稱:" + name);
      // 新的文件名
      String newFileName = this.getName(fileName);
      // 文件擴(kuò)展名
      String fileEnd = this.getFileExt(fileName);
      // 絕對路徑
      String fileNamedirs = logoRealPathDir + File.separator + newFileName + fileEnd;
      System.out.println("保存的絕對路徑:" + fileNamedirs);
      File filedirs = new File(fileNamedirs);
      // 轉(zhuǎn)入文件
      try {
        multipartFile.transferTo(filedirs);
      } catch (IllegalStateException 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();
      // 轉(zhuǎn)碼Avi
//      boolean flag = false;
      if (this.checkAVIType(fileEnd)) {
        // 設(shè)置轉(zhuǎn)換為AVI格式后文件的保存路徑
        String codcAviPath = logoRealPathDir + File.separator + newFileName + ".avi";
        // 獲取配置的轉(zhuǎn)換工具(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) {
        // 轉(zhuǎn)碼Flv
        if (this.checkMediaType(fileEnd)) {
          try {
            // 設(shè)置轉(zhuǎn)換為flv格式后文件的保存路徑
            String codcFilePath = logoRealPathDir + File.separator + newFileName + ".flv";
            // 獲取配置的轉(zhuǎn)換工具(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;
    }
  }
  /**
   * 文件類型判斷
   *
   * @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;
  }
  /**
   * 獲取文件擴(kuò)展名
   *
   * @return string
   */
  private String getFileExt(String fileName) {
    return fileName.substring(fileName.lastIndexOf("."));
  }
  /**
   * 依據(jù)原始文件名生成新文件名
   * @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 "";
  }
  /**
   * 文件大小,返回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 {
  /**
   * 視頻轉(zhuǎn)碼flv
   *
   * @param ffmpegPath
   *      轉(zhuǎn)碼工具的存放路徑
   * @param upFilePath
   *      用于指定要轉(zhuǎn)換格式的文件,要截圖的視頻源文件
   * @param codcFilePath
   *      格式轉(zhuǎn)換后的的文件保存路徑
   * @return
   * @throws Exception
   */
  public void processFLV(String ffmpegPath, String upFilePath, String codcFilePath) {
    // 創(chuàng)建一個(gè)List集合來保存轉(zhuǎn)換視頻文件為flv格式的命令
    List<String> convert = new ArrayList<String>();
    convert.add(ffmpegPath); // 添加轉(zhuǎn)換工具路徑
    convert.add("-i"); // 添加參數(shù)"-i",該參數(shù)指定要轉(zhuǎn)換的文件
    convert.add(upFilePath); // 添加要轉(zhuǎn)換格式的視頻文件的路徑
    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"); // 指定轉(zhuǎn)換的質(zhì)量 convert.add("6");
     * convert.add("-ab"); // 設(shè)置音頻碼率 convert.add("64"); convert.add("-ac");
     * // 設(shè)置聲道數(shù) convert.add("2"); convert.add("-ar"); // 設(shè)置聲音的采樣頻率
     * convert.add("22050"); convert.add("-r"); // 設(shè)置幀頻 convert.add("24");
     * convert.add("-y"); // 添加參數(shù)"-y",該參數(shù)指定將覆蓋已存在的文件
     */
    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();
    }
  }
  /**
   * 對ffmpeg無法解析的文件格式(wmv9,rm,rmvb等), 先用mencoder轉(zhuǎn)換為avi(ffmpeg能解析的)格式
   *
   * @param mencoderPath
   *      轉(zhuǎn)碼工具的存放路徑
   * @param upFilePath
   *      用于指定要轉(zhuǎn)換格式的文件,要截圖的視頻源文件
   * @param codcFilePath
   *      格式轉(zhuǎn)換后的的文件保存路徑
   * @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 {
      // 預(yù)處理進(jìn)程
      ProcessBuilder builder = new ProcessBuilder();
      builder.command(commend);
      builder.redirectErrorStream(true);
      // 進(jìn)程信息輸出到控制臺
      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();// 直到上面的命令執(zhí)行完,才向下執(zhí)行
      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();
    }
  }
}

實(shí)體類

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

總結(jié)

以上所述是小編給大家介紹的Java上傳視頻實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • Java編程實(shí)現(xiàn)提取文章中關(guān)鍵字的方法

    Java編程實(shí)現(xiàn)提取文章中關(guān)鍵字的方法

    這篇文章主要介紹了Java編程實(shí)現(xiàn)提取文章中關(guān)鍵字的方法,較為詳細(xì)的分析了Java提取文章關(guān)鍵字的原理與具體實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-11-11
  • maven-assembly-plugin報(bào)紅無法加載報(bào)錯:Plugin?‘maven-assembly-plugin:‘?not?found

    maven-assembly-plugin報(bào)紅無法加載報(bào)錯:Plugin?‘maven-assembly-plugin

    maven-assembly-plugin是一個(gè)常用的打包插件,但是在使用過程中經(jīng)常會遇到各種報(bào)錯,本文就來介紹一下maven-assembly-plugin報(bào)紅無法加載報(bào)錯,具有一定的參考價(jià)值
    2023-08-08
  • Java并發(fā)編程之詳解CyclicBarrier線程同步

    Java并發(fā)編程之詳解CyclicBarrier線程同步

    在之前的文章中已經(jīng)為大家介紹了java并發(fā)編程的工具:BlockingQueue接口,ArrayBlockingQueue,DelayQueue,LinkedBlockingQueue,PriorityBlockingQueue,SynchronousQueue,BlockingDeque接口,ConcurrentHashMap,CountDownLatch,本文為系列文章第十篇,需要的朋友可以參考下
    2021-06-06
  • Spring Boot配置動態(tài)更新問題

    Spring Boot配置動態(tài)更新問題

    這篇文章主要介紹了Spring Boot配置動態(tài)更新問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 什么情況下會出現(xiàn)java.io.IOException?:?Broken?pipe這個(gè)錯誤以及解決辦法

    什么情況下會出現(xiàn)java.io.IOException?:?Broken?pipe這個(gè)錯誤以及解決辦法

    這篇文章主要介紹了什么情況下會出現(xiàn)java.io.IOException?:?Broken?pipe這個(gè)錯誤以及解決辦法的相關(guān)資料,這個(gè)錯誤表示通信另一端已關(guān)閉連接,常發(fā)生在客戶端關(guān)閉連接、網(wǎng)絡(luò)超時(shí)或資源不足等情況,文中將解決辦法介紹的非常詳細(xì),需要的朋友可以參考下
    2024-10-10
  • 分析Spring框架之設(shè)計(jì)與實(shí)現(xiàn)資源加載器

    分析Spring框架之設(shè)計(jì)與實(shí)現(xiàn)資源加載器

    Spring框架是由于軟件開發(fā)的復(fù)雜性而創(chuàng)建的。然而,Spring的用途不僅僅限于服務(wù)器端的開發(fā)。從簡單性、可測試性和松耦合性角度而言,絕大部分Java應(yīng)用都可以從Spring中受益。今天來分析它的設(shè)計(jì)與實(shí)現(xiàn)資源加載器,從Spring.xml解析和注冊Bean對象
    2021-06-06
  • SpringBoot?Web依賴教程

    SpringBoot?Web依賴教程

    這篇文章主要介紹了SpringBoot?Web依賴教程,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • 利用Jackson實(shí)現(xiàn)數(shù)據(jù)脫敏的示例詳解

    利用Jackson實(shí)現(xiàn)數(shù)據(jù)脫敏的示例詳解

    在我們的企業(yè)項(xiàng)目中,為了保護(hù)用戶隱私,數(shù)據(jù)脫敏成了必不可少的操作,那么我們怎么優(yōu)雅的利用Jackson實(shí)現(xiàn)數(shù)據(jù)脫敏呢,本文就來和大家詳細(xì)聊聊,希望對大家有所幫助
    2023-05-05
  • Spring?Security登錄表單配置示例詳解

    Spring?Security登錄表單配置示例詳解

    這篇文章主要介紹了Spring?Security登錄表單配置,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-06-06
  • SpringBoot時(shí)間格式化的方法小結(jié)

    SpringBoot時(shí)間格式化的方法小結(jié)

    SpringBoot中的時(shí)間格式化通常指的是將Java中的日期時(shí)間類型轉(zhuǎn)換為指定格式的字符串,或者將字符串類型的時(shí)間解析為Java中的日期時(shí)間類型,本文小編將給大家詳細(xì)總結(jié)了SpringBoot時(shí)間格式化的方法,剛興趣的小伙伴跟著小編一起來看看吧
    2023-10-10

最新評論