当前位置:   article > 正文

JAVA上传图片/视频等文件_java上传视频和图片

java上传视频和图片

目前已测上传支持格式:{".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"{

允许视频转码的格式:{ ".wmv9", ".rm", ".rmvb" }

如需上传多文件,后台需要使用MultipartFile[] 数组接收,然后for循环fileUploadTool.createFile,多文件上传未做测试,有需要的小伙伴自行测试。

1,前端代码

  1. function testUploadVideo(){
  2. var fileObj = document.getElementById("file").files[0]; //获取文件对象
  3. var formFile = new FormData();
  4. formFile.append("param", "100"); //传入需要传的参数
  5. formFile.append("file", fileObj); // 加入文件对象
  6. var data = formFile;
  7. $.ajax({
  8. url : "../../lecture/uploadflv/uploadSave.action",
  9. type : "post",
  10. data : data,
  11. cache : false,// 上传文件无需缓存
  12. processData : false,// 用于对data参数进行序列化处理 这里必须false
  13. contentType : false, // 必须
  14. success : function(res) {
  15. alert("生成成功");
  16. alert(JSON.parse(res).result); //接收前台返回json字符串
  17. },
  18. error : function() {
  19. alert("生成失败");
  20. }
  21. })
  22. }
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <!-- <html xmlns="http://www.w3.org/1999/xhtml"> -->
  3. <html lang="zh" xmlns:th="http://www.thymeleaf.org">
  4. <head>
  5. <meta charset="utf-8">
  6. <meta http-equiv="Content-Type" content="text/html" />
  7. <meta name="viewport"
  8. content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  9. <script src="../js/jquery.min.js"></script>
  10. <script type="text/javascript" src="../js/jquery.touchSwipe.min.js"></script>
  11. <link rel="stylesheet" href="../css/indexpage.css">
  12. <script src="/lecture/html/indexpage/indexpage.js"></script>
  13. <title>视频图片测试页</title>
  14. </head>
  15. <body>
  16. <form class="" id="upload" method="post" enctype="multipart/form-data">
  17. <div >
  18. <input type="file" class="form-control" name="file" id="file"><br>
  19. <!-- <button id="testUploadVideo" type="button" onclick="testUploadVideo()">上传but</button> -->
  20. <a id="testUploadVideo" onclick="testUploadVideo()" >上传</a>
  21. </div>
  22. </form>
  23. </body>
  24. </html>

 

2,控制器

  1. package com.ejfee.tw.twweb.videoupload.controller;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.ModelMap;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import com.alibaba.fastjson.JSON;
  12. import com.ejfee.tw.twweb.videoupload.domain.FileEntity;
  13. import com.ejfee.tw.twweb.videoupload.util.FileUploadTool;
  14. @Controller
  15. @RequestMapping("uploadflv")
  16. public class UploadController {
  17. @RequestMapping(value = "uploadSave", method = RequestMethod.POST)
  18. @ResponseBody
  19. public void upload(@RequestParam(value = "file", required = false) MultipartFile multipartFile, HttpServletRequest request,
  20. HttpServletResponse response, ModelMap map,String param) {
  21. response.setContentType("text/html;charset=UTF-8"); //设置返回值编码格式
  22. String a = request.getParameter("param");
  23. String message = "";
  24. FileEntity entity = new FileEntity();
  25. FileUploadTool fileUploadTool = new FileUploadTool();
  26. try {
  27. entity = fileUploadTool.createFile(multipartFile, request);
  28. if (entity != null) {
  29. // service.saveFile(entity); //将视频上传路径,视频名称,视频时长等内容保存至数据库
  30. message = "SUCCESS";
  31. map.put("entity", entity);
  32. map.put("result", message);
  33. } else {
  34. message = "FAIL";
  35. map.put("result", message);
  36. }
  37. response.getWriter().write(JSON.toJSONString(map));
  38. } catch (Exception e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }

 

3,实体类

  1. package com.ejfee.tw.twweb.videoupload.domain;
  2. import java.sql.Timestamp;
  3. public class FileEntity {
  4. private String type;
  5. private String size;
  6. private String path;
  7. private String titleOrig;
  8. private String titleAlter;
  9. private Timestamp uploadTime;
  10. public String getType() {
  11. return type;
  12. }
  13. public void setType(String type) {
  14. this.type = type;
  15. }
  16. public String getSize() {
  17. return size;
  18. }
  19. public void setSize(String size) {
  20. this.size = size;
  21. }
  22. public String getPath() {
  23. return path;
  24. }
  25. public void setPath(String path) {
  26. this.path = path;
  27. }
  28. public String getTitleOrig() {
  29. return titleOrig;
  30. }
  31. public void setTitleOrig(String titleOrig) {
  32. this.titleOrig = titleOrig;
  33. }
  34. public String getTitleAlter() {
  35. return titleAlter;
  36. }
  37. public void setTitleAlter(String titleAlter) {
  38. this.titleAlter = titleAlter;
  39. }
  40. public Timestamp getUploadTime() {
  41. return uploadTime;
  42. }
  43. public void setUploadTime(Timestamp uploadTime) {
  44. this.uploadTime = uploadTime;
  45. }
  46. }

4,util 方法类

  1. package com.ejfee.tw.twweb.videoupload.util;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.sql.Timestamp;
  5. import java.text.DecimalFormat;
  6. import java.util.Arrays;
  7. import java.util.Iterator;
  8. import javax.servlet.http.HttpServletRequest;
  9. import org.springframework.web.multipart.MultipartFile;
  10. import com.ejfee.tw.twweb.videoupload.domain.FileEntity;
  11. public class FileUploadTool {
  12. TransfMediaTool transfMediaTool = new TransfMediaTool();
  13. // 文件最大500M
  14. private static long upload_maxsize = 800 * 1024 * 1024;
  15. // 文件允许格式
  16. private static String[] allowFiles = { ".rar", ".doc", ".docx", ".zip",
  17. ".pdf", ".txt", ".swf", ".xlsx", ".gif", ".png", ".jpg", ".jpeg",
  18. ".bmp", ".xls", ".mp4", ".flv", ".ppt", ".avi", ".mpg", ".wmv",
  19. ".3gp", ".mov", ".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb" };
  20. // 允许转码的视频格式(ffmpeg)
  21. private static String[] allowFLV = { ".avi", ".mpg", ".wmv", ".3gp",
  22. ".mov", ".asf", ".asx", ".vob" };
  23. // 允许的视频转码格式(mencoder)
  24. private static String[] allowAVI = { ".wmv9", ".rm", ".rmvb" };
  25. public FileEntity createFile(MultipartFile multipartFile, HttpServletRequest request) {
  26. FileEntity entity = new FileEntity();
  27. boolean bflag = false;
  28. String fileName = multipartFile.getOriginalFilename().toString();
  29. // 判断文件不为空
  30. if (multipartFile.getSize() != 0 && !multipartFile.isEmpty()) {
  31. bflag = true;
  32. // 判断文件大小
  33. if (multipartFile.getSize() <= upload_maxsize) {
  34. bflag = true;
  35. // 文件类型判断
  36. if (this.checkFileType(fileName)) {
  37. bflag = true;
  38. } else {
  39. bflag = false;
  40. System.out.println("文件类型错误");
  41. }
  42. } else {
  43. bflag = false;
  44. System.out.println("文件大小超范围");
  45. }
  46. } else {
  47. bflag = false;
  48. System.out.println("文件为空");
  49. }
  50. if (bflag) {
  51. String logoPathDir = "/video/";
  52. // 上传到本地磁盘
  53. // String logoRealPathDir = "E:/upload";
  54. // request.getServletContext().getRealPath("/")
  55. // String logoRealPathDir = request.getSession().getServletContext().getRealPath("/videoAndImage/video");
  56. String logoRealPathDir = "E:/upload";
  57. File logoSaveFile = new File(logoRealPathDir);
  58. if (!logoSaveFile.exists()) {
  59. logoSaveFile.mkdirs();
  60. }
  61. String name = fileName.substring(0, fileName.lastIndexOf("."));
  62. System.out.println("文件名称:" + name);
  63. // 新的文件名
  64. String newFileName = this.getName(fileName);
  65. // 文件扩展名
  66. String fileEnd = this.getFileExt(fileName);
  67. // 绝对路径
  68. String fileNamedirs = logoRealPathDir + File.separator + newFileName + fileEnd;
  69. System.out.println("保存的绝对路径:" + fileNamedirs);
  70. File filedirs = new File(fileNamedirs);
  71. // 转入文件
  72. try {
  73. multipartFile.transferTo(filedirs);
  74. } catch (IllegalStateException e) {
  75. e.printStackTrace();
  76. } catch (IOException e) {
  77. e.printStackTrace();
  78. }
  79. // 相对路径
  80. entity.setType(fileEnd);
  81. String fileDir = logoPathDir + newFileName + fileEnd;
  82. StringBuilder builder = new StringBuilder(fileDir);
  83. String finalFileDir = builder.substring(1);
  84. // size存储为String
  85. String size = this.getSize(filedirs);
  86. // 源文件保存路径
  87. String aviPath = filedirs.getAbsolutePath();
  88. // 转码Avi
  89. // boolean flag = false;
  90. if (this.checkAVIType(fileEnd)) {
  91. // 设置转换为AVI格式后文件的保存路径
  92. String codcAviPath = logoRealPathDir + File.separator + newFileName + ".avi";
  93. // 获取配置的转换工具(mencoder.exe)的存放路径
  94. String mencoderPath = request.getSession().getServletContext().getRealPath("/tools/mencoder.exe");
  95. aviPath = transfMediaTool.processAVI(mencoderPath, filedirs.getAbsolutePath(), codcAviPath);
  96. fileEnd = this.getFileExt(codcAviPath);
  97. }
  98. if (aviPath != null) {
  99. // 转码Flv
  100. if (this.checkMediaType(fileEnd)) {
  101. try {
  102. // 设置转换为flv格式后文件的保存路径
  103. String codcFilePath = logoRealPathDir + File.separator + newFileName + ".flv";
  104. // 获取配置的转换工具(ffmpeg.exe)的存放路径
  105. String ffmpegPath = request.getSession().getServletContext().getRealPath("/tools/ffmpeg.exe");
  106. transfMediaTool.processFLV(ffmpegPath, aviPath, codcFilePath);
  107. fileDir = logoPathDir + newFileName + ".flv";
  108. builder = new StringBuilder(fileDir);
  109. finalFileDir = builder.substring(1);
  110. } catch (Exception e) {
  111. e.printStackTrace();
  112. }
  113. }
  114. entity.setSize(size);
  115. entity.setPath(finalFileDir);
  116. entity.setTitleOrig(name);
  117. entity.setTitleAlter(newFileName);
  118. Timestamp timestamp = new Timestamp(System.currentTimeMillis());
  119. entity.setUploadTime(timestamp);
  120. //可以再此处将视频上传路径,视频名称,视频时长等内容保存至数据库
  121. return entity;
  122. } else {
  123. return null;
  124. }
  125. } else {
  126. return null;
  127. }
  128. }
  129. /**
  130. * 文件类型判断
  131. *
  132. * @param fileName
  133. * @return
  134. */
  135. private boolean checkFileType(String fileName) {
  136. Iterator<String> type = Arrays.asList(allowFiles).iterator();
  137. while (type.hasNext()) {
  138. String ext = type.next();
  139. if (fileName.toLowerCase().endsWith(ext)) {
  140. return true;
  141. }
  142. }
  143. return false;
  144. }
  145. /**
  146. * 视频类型判断(flv)
  147. *
  148. * @param fileName
  149. * @return
  150. */
  151. private boolean checkMediaType(String fileEnd) {
  152. Iterator<String> type = Arrays.asList(allowFLV).iterator();
  153. while (type.hasNext()) {
  154. String ext = type.next();
  155. if (fileEnd.equals(ext)) {
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * 视频类型判断(AVI)
  163. *
  164. * @param fileName
  165. * @return
  166. */
  167. private boolean checkAVIType(String fileEnd) {
  168. Iterator<String> type = Arrays.asList(allowAVI).iterator();
  169. while (type.hasNext()) {
  170. String ext = type.next();
  171. if (fileEnd.equals(ext)) {
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. /**
  178. * 获取文件扩展名
  179. *
  180. * @return string
  181. */
  182. private String getFileExt(String fileName) {
  183. return fileName.substring(fileName.lastIndexOf("."));
  184. }
  185. /**
  186. * 依据原始文件名生成新文件名
  187. * @return
  188. */
  189. private String getName(String fileName) {
  190. Iterator<String> type = Arrays.asList(allowFiles).iterator();
  191. while (type.hasNext()) {
  192. String ext = type.next();
  193. if (fileName.contains(ext)) {
  194. String newFileName = fileName.substring(0, fileName.lastIndexOf(ext));
  195. return newFileName;
  196. }
  197. }
  198. return "";
  199. }
  200. /**
  201. * 文件大小,返回kb.mb
  202. *
  203. * @return
  204. */
  205. private String getSize(File file) {
  206. String size = "";
  207. long fileLength = file.length();
  208. DecimalFormat df = new DecimalFormat("#.00");
  209. if (fileLength < 1024) {
  210. size = df.format((double) fileLength) + "BT";
  211. } else if (fileLength < 1048576) {
  212. size = df.format((double) fileLength / 1024) + "KB";
  213. } else if (fileLength < 1073741824) {
  214. size = df.format((double) fileLength / 1048576) + "MB";
  215. } else {
  216. size = df.format((double) fileLength / 1073741824) + "GB";
  217. }
  218. return size;
  219. }
  220. }
  1. package com.ejfee.tw.twweb.videoupload.util;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. public class TransfMediaTool {
  8. /**
  9. * 视频转码flv
  10. *
  11. * @param ffmpegPath
  12. * 转码工具的存放路径
  13. * @param upFilePath
  14. * 用于指定要转换格式的文件,要截图的视频源文件
  15. * @param codcFilePath
  16. * 格式转换后的的文件保存路径
  17. * @return
  18. * @throws Exception
  19. */
  20. public void processFLV(String ffmpegPath, String upFilePath, String codcFilePath) {
  21. // 创建一个List集合来保存转换视频文件为flv格式的命令
  22. List<String> convert = new ArrayList<String>();
  23. convert.add(ffmpegPath); // 添加转换工具路径
  24. convert.add("-i"); // 添加参数"-i",该参数指定要转换的文件
  25. convert.add(upFilePath); // 添加要转换格式的视频文件的路径
  26. convert.add("-ab");
  27. convert.add("56");
  28. convert.add("-ar");
  29. convert.add("22050");
  30. convert.add("-q:a");
  31. convert.add("8");
  32. convert.add("-r");
  33. convert.add("15");
  34. convert.add("-s");
  35. convert.add("600*500");
  36. /*
  37. * convert.add("-qscale"); // 指定转换的质量 convert.add("6");
  38. * convert.add("-ab"); // 设置音频码率 convert.add("64"); convert.add("-ac");
  39. * // 设置声道数 convert.add("2"); convert.add("-ar"); // 设置声音的采样频率
  40. * convert.add("22050"); convert.add("-r"); // 设置帧频 convert.add("24");
  41. * convert.add("-y"); // 添加参数"-y",该参数指定将覆盖已存在的文件
  42. */
  43. convert.add(codcFilePath);
  44. try {
  45. Process videoProcess = new ProcessBuilder(convert).redirectErrorStream(true).start();
  46. new PrintStream(videoProcess.getInputStream()).start();
  47. videoProcess.waitFor();
  48. } catch (IOException e1) {
  49. e1.printStackTrace();
  50. } catch (InterruptedException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. /**
  55. * 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等), 先用mencoder转换为avi(ffmpeg能解析的)格式
  56. *
  57. * @param mencoderPath
  58. * 转码工具的存放路径
  59. * @param upFilePath
  60. * 用于指定要转换格式的文件,要截图的视频源文件
  61. * @param codcFilePath
  62. * 格式转换后的的文件保存路径
  63. * @return
  64. * @throws Exception
  65. */
  66. public String processAVI(String mencoderPath, String upFilePath, String codcAviPath) {
  67. // boolean flag = false;
  68. List<String> commend = new ArrayList<String>();
  69. commend.add(mencoderPath);
  70. commend.add(upFilePath);
  71. commend.add("-oac");
  72. commend.add("mp3lame");
  73. commend.add("-lameopts");
  74. commend.add("preset=64");
  75. commend.add("-lavcopts");
  76. commend.add("acodec=mp3:abitrate=64");
  77. commend.add("-ovc");
  78. commend.add("xvid");
  79. commend.add("-xvidencopts");
  80. commend.add("bitrate=600");
  81. commend.add("-of");
  82. commend.add("avi");
  83. commend.add("-o");
  84. commend.add(codcAviPath);
  85. try {
  86. // 预处理进程
  87. ProcessBuilder builder = new ProcessBuilder();
  88. builder.command(commend);
  89. builder.redirectErrorStream(true);
  90. // 进程信息输出到控制台
  91. Process p = builder.start();
  92. BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
  93. String line = null;
  94. while ((line = br.readLine()) != null) {
  95. System.out.println(line);
  96. }
  97. p.waitFor();// 直到上面的命令执行完,才向下执行
  98. return codcAviPath;
  99. } catch (Exception e) {
  100. e.printStackTrace();
  101. return null;
  102. }
  103. }
  104. }
  105. class PrintStream extends Thread {
  106. java.io.InputStream __is = null;
  107. public PrintStream(java.io.InputStream is) {
  108. __is = is;
  109. }
  110. public void run() {
  111. try {
  112. while (this != null) {
  113. int _ch = __is.read();
  114. if (_ch != -1)
  115. System.out.print((char) _ch);
  116. else
  117. break;
  118. }
  119. } catch (Exception e) {
  120. e.printStackTrace();
  121. }
  122. }
  123. }

 

 

  1. // 判断文件夹是否存在
  2. public static void judeDirExists() {
  3. File file = new File("d:\\test_dir");
  4. if (file.exists()) {
  5. //如果存在则不操作
  6. //if (file.isDirectory()) { //isDirectory判断此对象是否为文件夹
  7. // System.out.println("dir exists");
  8. //} else {
  9. // System.out.println("the same name file exists, can not create dir");
  10. //}
  11. } else {
  12. //不存在则创建
  13. System.out.println("dir not exists, create it ...");
  14. file.mkdir();
  15. }
  16. }

 

注:部分代码转载自https://www.cnblogs.com/smart-hwt/p/8256836.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/267865
推荐阅读
相关标签
  

闽ICP备14008679号