当前位置:Gxlcms > AJAX > ajax 异步上传带进度条视频并提取缩略图

ajax 异步上传带进度条视频并提取缩略图

时间:2021-07-01 10:21:17 帮助过:29人阅读

最近在做一个集富媒体功能于一身的项目。需要上传视频。这里我希望做成异步上传,并且有进度条,响应有状态码,视频连接,缩略图。

服务端响应

  1. {
  2. "thumbnail": "/slsxpt//upload/thumbnail/fdceefc.jpg",
  3. "success": true,
  4. "link": "/slsxpt//upload/video/fdceefc.mp"
  5. }

并且希望我的input file控件不要被form标签包裹。原因是form中不能嵌套form,另外form标签在浏览器了还是有一点点默认样式的,搞不好又要写css。

以前用ajaxFileUpload做过文件异步上传。不过这个东西好久未更新,代码还有bug,虽然最后勉强成功用上了,但总觉不好。而且ajaxFileUpload没有直接添加xhr2的progress事件响应,比较麻烦。

上网找了一下,发现方法都是很多。

比如在文件上传后,将上传进度放到session中,轮询服务器session。但我总觉的这个方法有问题,我认为这种方法看到的进度,应该是我的服务端应用程序代码(我的也就是action)从服务器的临时目录复制文件的进度,因为所有请求都应该先提交给服务器软件,也就是tomcat,tomcat对请求进行封装session,request等对象,并且文件实际上也应该是它来接收的。也就是说在我的action代码执行之前,文件实际上已经上传完毕了。

后来找到个比较好的方法使用 jquery.form.js插件的ajaxSubmit方法。这个方法以表单来提交,也就是 $.fn.ajaxSubmit.:$(form selector).ajaxSubmit({}),这个api的好处是它已经对xhr2的progress时间进行了处理,可以在调用时传递一个uploadProgress的function,在function里就能够拿到进度。而且如果不想input file被form包裹也没关系,在代码里createElement应该可以。不过这个方法我因为犯了个小错误最后没有成功,可惜了。

ajaxSubmit源码

最后,还是使用了$.ajax 方法来做。$.ajax 不需要关联form,有点像个静态方法哦。唯一的遗憾就是$.ajax options里没有对progress的响应。不过它有一个参数为 xhr ,也就是你可以定制xhr,那么久可以通过xhr添加progress的事件处理程序。再结合看一看ajaxSubmit方法里对progress事件的处理,顿时豁然开朗

那么我也可以在$.ajax 方法中添加progress事件处理函数了。为了把对dom的操作从上传业务中抽取出来,我决定以插件的形式写。下面是插件的代码

  1. ;(function ($) {
  2. var defaults = {
  3. uploadProgress : null,
  4. beforeSend : null,
  5. success : null,
  6. },
  7. setting = {
  8. };
  9. var upload = function($this){
  10. $this.parent().on('change',$this,function(event){
  11. //var $this = $(event.target),
  12. var formData = new FormData(),
  13. target = event.target || event.srcElement;
  14. //$.each(target.files, function(key, value)
  15. //{
  16. // console.log(key);
  17. // formData.append(key, value);
  18. //});
  19. formData.append('file',target.files[]);
  20. settings.fileType && formData.append('fileType',settings.fileType);
  21. $.ajax({
  22. url : $this.data('url'),
  23. type : "POST",
  24. data : formData,
  25. dataType : 'json',
  26. processData : false,
  27. contentType : false,
  28. cache : false,
  29. beforeSend : function(){
  30. //console.log('start');
  31. if(settings.beforeSend){
  32. settings.beforeSend();
  33. }
  34. },
  35. xhr : function() {
  36. var xhr = $.ajaxSettings.xhr();
  37. if(xhr.upload){
  38. xhr.upload.addEventListener('progress',function(event){
  39. var total = event.total,
  40. position = event.loaded || event.position,
  41. percent = ;
  42. if(event.lengthComputable){
  43. percent = Math.ceil(position / total * );
  44. }
  45. if(settings.uploadProgress){
  46. settings.uploadProgress(event, position, total, percent);
  47. }
  48. }, false);
  49. }
  50. return xhr;
  51. },
  52. success : function(data,status,jXhr){
  53. if(settings.success){
  54. settings.success(data);
  55. }
  56. },
  57. error : function(jXhr,status,error){
  58. if(settings.error){
  59. settings.error(jXhr,status,error);
  60. }
  61. }
  62. });
  63. });
  64. };
  65. $.fn.uploadFile = function (options) {
  66. settings = $.extend({}, defaults, options);
  67. // 文件上传
  68. return this.each(function(){
  69. upload($(this));
  70. });
  71. }
  72. })($ || jQuery);

下面就可以在我的jsp页面里面使用这个api了。

  1. <div class="col-sm-">
  2. <input type="text" name="resource_url" id="resource_url" hidden="hidden"/>
  3. <div class="progress" style='display: none;'>
  4. <div class="progress-bar progress-bar-success uploadVideoProgress" role="progressbar"
  5. aria-valuenow="" aria-valuemin="" aria-valuemax="" style="width: %">
  6. </div>
  7. </div>
  8. <input type="file" class="form-control file inline btn btn-primary uploadInput uploadVideo"
  9. accept="video/mp"
  10. data-url="${baseUrl}/upload-video.action"
  11. data-label="<i class='glyphicon glyphicon-circle-arrow-up'></i>  选择文件" />
  12. <script>
  13. (function($){
  14. $(document).ready(function(){
  15. var $progress = $('.uploadVideoProgress'),
  16. start = false;
  17. $('input.uploadInput.uploadVideo').uploadFile({
  18. beforeSend : function(){
  19. $progress.parent().show();
  20. },
  21. uploadProgress : function(event, position, total, percent){
  22. $progress.attr('aria-valuenow',percent);
  23. $progress.width(percent+'%');
  24. if(percent >= ){
  25. $progress.parent().hide();
  26. $progress.attr('aria-valuenow',);
  27. $progress.width(+'%');
  28. }
  29. },
  30. success : function(data){
  31. if(data.success){
  32. setTimeout(function(){
  33. $('#thumbnail').attr('src',data.thumbnail);
  34. },);
  35. }
  36. }
  37. });
  38. });
  39. })(jQuery);
  40. </script>
  41. </div>

这里在响应succes的时候设置超时800毫秒之后获取图片,因为提取缩量图是另一个进程在做可能响应完成的时候缩略图还没提取完成

看下效果

提取缩量图

下面部分就是服务端处理上传,并且对视频提取缩量图下面是action的处理代码

  1. package org.lyh.app.actions;
  2. import org.apache.commons.io.FileUtils;
  3. import org.apache.struts.ServletActionContext;
  4. import org.lyh.app.base.BaseAction;
  5. import org.lyh.library.SiteHelpers;
  6. import org.lyh.library.VideoUtils;
  7. import java.io.File;
  8. import java.io.IOException;
  9. import java.security.KeyStore;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. /**
  13. * Created by admin on //.
  14. */
  15. public class UploadAction extends BaseAction{
  16. private String saveBasePath;
  17. private String imagePath;
  18. private String videoPath;
  19. private String audioPath;
  20. private String thumbnailPath;
  21. private File file;
  22. private String fileFileName;
  23. private String fileContentType;
  24. // 省略setter getter方法
  25. public String video() {
  26. Map<String, Object> dataJson = new HashMap<String, Object>();
  27. System.out.println(file);
  28. System.out.println(fileFileName);
  29. System.out.println(fileContentType);
  30. String fileExtend = fileFileName.substring(fileFileName.lastIndexOf("."));
  31. String newFileName = SiteHelpers.md(fileFileName + file.getTotalSpace());
  32. String typeDir = "normal";
  33. String thumbnailName = null,thumbnailFile = null;
  34. boolean needThumb = false,extractOk = false;
  35. if (fileContentType.contains("video")) {
  36. typeDir = videoPath;
  37. // 提取缩量图
  38. needThumb = true;
  39. thumbnailName = newFileName + ".jpg";
  40. thumbnailFile
  41. = app.getRealPath(saveBasePath + thumbnailPath) + "/" + thumbnailName;
  42. }
  43. String realPath = app.getRealPath(saveBasePath + typeDir);
  44. File saveFile = new File(realPath, newFileName + fileExtend);
  45. // 存在同名文件,跳过
  46. if (!saveFile.exists()) {
  47. if (!saveFile.getParentFile().exists()) {
  48. saveFile.getParentFile().mkdirs();
  49. }
  50. try {
  51. FileUtils.copyFile(file, saveFile);
  52. if(needThumb){
  53. extractOk = VideoUtils.extractThumbnail(saveFile, thumbnailFile);
  54. System.out.println("提取缩略图成功:"+extractOk);
  55. }
  56. dataJson.put("success", true);
  57. } catch (IOException e) {
  58. System.out.println(e.getMessage());
  59. dataJson.put("success", false);
  60. }
  61. }else{
  62. dataJson.put("success", true);
  63. }
  64. if((Boolean)dataJson.get("success")){
  65. dataJson.put("link",
  66. app.getContextPath() + "/" + saveBasePath + typeDir + "/" + newFileName + fileExtend);
  67. if(needThumb){
  68. dataJson.put("thumbnail",
  69. app.getContextPath() + "/" + saveBasePath + thumbnailPath + "/" + thumbnailName);
  70. }
  71. }
  72. this.responceJson(dataJson);
  73. return NONE;
  74. }
  75. }

action配置

  1. <action name="upload-*" class="uploadAction" method="{}">
  2. <param name="saveBasePath">/upload</param>
  3. <param name="imagePath">/images</param>
  4. <param name="videoPath">/video</param>
  5. <param name="audioPath">/audio</param>
  6. <param name="thumbnailPath">/thumbnail</param>
  7. </action>

这里个人认为,如果文件的名称跟大小完全一样的话,它们是一个文件的概率就非常大了,所以我这里取文件名跟文件大小做md5运算,应该可以稍微避免下重复上传相同文件了。

转码的时候用到FFmpeg。需要的可以去这里下载。

  1. package org.lyh.library;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. /**
  8. * Created by admin on //.
  9. */
  10. public class VideoUtils {
  11. public static final String FFMPEG_EXECUTOR = "C:/Software/ffmpeg.exe";
  12. public static final int THUMBNAIL_WIDTH = ;
  13. public static final int THUMBNAIL_HEIGHT = ;
  14. public static boolean extractThumbnail(File inputFile,String thumbnailOutput){
  15. List<String> command = new ArrayList<String>();
  16. File ffmpegExe = new File(FFMPEG_EXECUTOR);
  17. if(!ffmpegExe.exists()){
  18. System.out.println("转码工具不存在");
  19. return false;
  20. }
  21. System.out.println(ffmpegExe.getAbsolutePath());
  22. System.out.println(inputFile.getAbsolutePath());
  23. command.add(ffmpegExe.getAbsolutePath());
  24. command.add("-i");
  25. command.add(inputFile.getAbsolutePath());
  26. command.add("-y");
  27. command.add("-f");
  28. command.add("image");
  29. command.add("-ss");
  30. command.add("");
  31. command.add("-t");
  32. command.add(".");
  33. command.add("-s");
  34. command.add(THUMBNAIL_WIDTH+"*"+THUMBNAIL_HEIGHT);
  35. command.add(thumbnailOutput);
  36. ProcessBuilder builder = new ProcessBuilder();
  37. builder.command(command);
  38. builder.redirectErrorStream(true);
  39. try {
  40. long startTime = System.currentTimeMillis();
  41. Process process = builder.start();
  42. System.out.println("启动耗时"+(System.currentTimeMillis()-startTime));
  43. return true;
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. return false;
  47. }
  48. }
  49. }

另外这里由java启动了另外一个进程,在我看来他们应该是互不相干的,java启动了ffmpeg.exe之后,应该回来继续执行下面的代码,所以并不需要单独起一个线程去提取缩量图。测试看也发现耗时不多。每次长传耗时也区别不大,下面是两次上传同一个文件耗时

第一次

第二次

就用户体验来说没有很大的区别。

另外这里上传较大文件需要对tomcat和struct做点配置

修改tomcat下conf目录下的server.xml文件,为Connector节点添加属性 maxPostSize="0"表示不显示上传大小

另外修改 struts.xml添加配置,这里的value单位为字节,这里大概300多mb

人气教程排行