Java上傳視頻

来源:https://www.cnblogs.com/smart-hwt/archive/2018/01/10/8256836.html
-Advertisement-
Play Games

頁面: 上傳文件時的關鍵詞:enctype="multipart/form-data" 後臺:controller 工具類 實體類 ...


頁面:

上傳文件時的關鍵詞: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%>">
    <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" }; // 允許轉碼的視頻格式(ffmpeg) private static String[] allowFLV = { ".avi", ".mpg", ".wmv", ".3gp", ".mov", ".asf", ".asx", ".vob" }; // 允許的視頻轉碼格式(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); // 文件擴展名 String fileEnd = this.getFileExt(fileName); // 絕對路徑 String fileNamedirs = logoRealPathDir + File.separator + newFileName + fileEnd; System.out.println("保存的絕對路徑:" + fileNamedirs); File filedirs = new File(fileNamedirs); // 轉入文件 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(); // 轉碼Avi // boolean flag = 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(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; } /** * 獲取文件擴展名 * * @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)); 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 {
    
    /**
     * 視頻轉碼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();
        }
    }

    /**
     * 對ffmpeg無法解析的文件格式(wmv9,rm,rmvb等), 先用mencoder轉換為avi(ffmpeg能解析的)格式
     *
     * @param mencoderPath
     *            轉碼工具的存放路徑
     * @param upFilePath
     *            用於指定要轉換格式的文件,要截圖的視頻源文件
     * @param codcFilePath
     *            格式轉換後的的文件保存路徑
     * @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 {
            // 預處理進程
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            builder.redirectErrorStream(true);

            // 進程信息輸出到控制台
            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();// 直到上面的命令執行完,才向下執行
            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();
        }
    }
}

實體類

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

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • FCC-學習筆記 Sorted Union 1>最近在學習和練習FCC的題目。這個真的比較的好,推薦給大家。 2>中文版的地址:https://www.freecodecamp.cn/;英文版的地址:https://www.freecodecamp.org 3>這次寫關於一個JS的問題,名為Sort ...
  • HTML 中 script 標簽可以載入其他域下的js,比如我們經常引入一個其他域下線上cdn的jQuery。那如何利用這個特性實現從其他域下獲取數據呢? 可以先這樣試試: 這時候會向天氣介面發送請求獲取數據,獲取數據後做為 js 來執行。 但這裡有個問題, 數據是 JSON 格式的數據,直接作為 ...
  • FCC-學習筆記 Boo who 1>最近在學習和練習FCC的題目。這個真的比較的好,推薦給大家。 2>中文版的地址:https://www.freecodecamp.cn/;英文版的地址:https://www.freecodecamp.org 3>這次寫關於一個JS的問題,名為Pig Latin ...
  • FCC-學習筆記 Missing letters 1>最近在學習和練習FCC的題目。這個真的比較的好,推薦給大家。 2>中文版的地址:https://www.freecodecamp.cn/;英文版的地址:https://www.freecodecamp.org 3>這次寫關於一個JS的問題,名為M ...
  • FCC-學習筆記 DNA Pairing 1>最近在學習和練習FCC的題目。這個真的比較的好,推薦給大家。 2>中文版的地址:https://www.freecodecamp.cn/;英文版的地址:https://www.freecodecamp.org 3>這次寫關於一個JS的問題,名為DNA P ...
  • 一、安裝實例 1、創建實例目錄 [root@node004]# mkdir -p /usr/local/solr/home/jonychen 2、複製實例相關配置文件 [root@node004]# cp /usr/local/solr/home/configsets/_default/conf - ...
  • 設計模式(Design Patterns) 一、設計模式的分類 總體來說設計模式分為三大類: 創建型模式,共五種:工廠方法模式、抽象工廠模式、單例模式、建造者模式、原型模式。 結構型模式,共七種:適配器模式、裝飾器模式、代理模式、外觀模式、橋接模式、組合模式、享元模式。 行為型模式,共十一種:策略模 ...
  • 在主流的Web站點中,圖片往往是不可或缺的頁面元素,尤其在大型網站中,幾乎都將面臨“海量圖片資源”的存儲、訪問等相關技術問題。在針對圖片伺服器的架構擴展中,也會歷經很多曲折甚至是血淚教訓(尤其是早期規劃不足,造成後期架構上很難相容和擴展)。 本文將以一個真實垂直門戶網站的發展歷程,向大家娓娓道來。 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...