Java上传视频实例代码
作者:smart_hwt 发布时间:2023-06-24 04:17:45
标签:java,上传视频
页面:
上传文件时的关键词: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" };
// 允许转码的视频格式(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;
}
}
总结
以上所述是小编给大家介绍的Java上传视频实例代码网站的支持!
来源:https://www.cnblogs.com/smart-hwt/archive/2018/01/10/8256836.html


猜你喜欢
- 本文实例讲述了Android开发使用Handler的PostDelayed方法实现图片轮播功能。分享给大家供大家参考,具体如下:第一步:创建
- 服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 
- Android自定义实现图片加文字功能分四步来写: 1,组合控件的xml; 2,自定义组合控件的属性; 3,自定义继承组合布局的class类
- 今天在码代码的时候突然想到这个问题,觉得有点困惑。在网上也翻阅不少帖子其中有一个帖子给了我一个思路,其实也是解释了基础概念。概念一:try
- tokentoken的意思是“令牌”,是用户身份的验证方式,最简单的token组成:uid(用户唯一的身份标识)、time(当前时间的时间戳
- 本文实例讲述了基于C#实现XML文件读取工具类。分享给大家供大家参考。具体如下:这是我去年写的一个XML文件读取工具类,现在做了一些调整 基
- 本文将介绍通过Java程序来读取PDF文档中的文本和图片的方法。分别调用方法extractText()和extractImages()来读取
- Intellij是进行scala开发的一个非常好用的工具,可以非常轻松查看scala源码,当然用它来开发Java也是很爽的,之前一直在用sc
- 一:SparkSQL1.SparkSQL简介Spark SQL是Spark的一个模块,用于处理结构化的数据,它提供了一个数据抽象DataFr
- 1.关系运算符!= 与等号共同组成关系运算符,检查两个操作数的值是否相等,如:A!=B2.逻辑运算符! 称为逻辑非运算符。用来逆转操作数的逻
- 效果图片重写DataGridView的OnRowPostPaint方法或者直接在DataGridView的RowPostPaint事件里写,
- vue3新增effectScope相关的API其官方的描述是创建一个 effect 作用域,可以捕获其中所创建的响应式副作用 (即计算属性和
- 条件:1、android:ellipsize=”marquee”2、TextView必须单行显示,即内容必须超出TextView
- 首先不可否认,这些在面试上会经常被面试官问起,但是你回答的让面试官满意吗?当然如果你知道了这些原理,或许你就不怕了。既然说到了原理,我们还是
- 前言List接口是Collection接口的三大接口之一,其中的数据可以通过位置检索,用户可以在指定位置插入数据。List的数据可以为空,可
- 本文实例讲述了java读取properties配置文件的方法。分享给大家供大家参考。具体分析如下:这两天做java项目,用到属性文件,到网上
- 当需要将一个对象输出到显示器时,通常要调用他的toString()方法,将对象的内容转换为字符串.java中的所有类默认都有一个toStri
- private static char[] constant = &
- 快速普及1、mybatis是什么 mybatis是一个支持普通SQL查询,存储过
- 前言一个说难不难,说简单竟看不出来是哪里问题的一个bug。是的 可能自己能力和经验尚浅无法识别,下面你们能否用火眼金睛一眼让bug原形毕露(