微信小程序_(校园视)  开发用户注册登陆  传送门

  微信小程序_(校园视)  开发上传视频业务  传送门

  微信小程序_(校园视)  开发视频的展示页-上  传送门

  微信小程序_(校园视)  开发视频的展示页-下  传送门

用户上传视频

  用户选择视频->打开选择bgm->选择/不选择bgm输入视频的描述->Controller上传视频->保存视频的截图->用户是否选择bgm

  用户没有选择bgm可以直接保存视频,用户选择bgm将合并原视频和bgm新的视频并且保存

  用户点击上传视频触发uploadVideo方法

  1. <button size='mini' class='primary' bindtap='uploadVideo'> 上传作品</button>
  1. uploadVideo:function(){
  2. var me =this;
  3. wx.chooseVideo({
  4. sourceType: ['album'],
  5. success(res) {
  6. console.log(res);
  7. }
  8. })
  9. }

  1. <view>
  2.  
  3. <view class='container'>
  4. <image src="{{faceUrl}}" class="face" bindtap='changeFace'></image>
  5.  
  6. <label class='nickname'>{{nickname}}</label>
  7.  
  8. <button size='mini' class='primary' bindtap='uploadVideo'> 上传作品</button>
  9. <button size='mini' type='' class='logout' bindtap='logout'>注销</button>
  10.  
  11. <view class='container-row'>
  12. <label class='info-items'>{{fansCounts}} 粉丝</label>
  13. <label class='info-items'>{{followCounts}} 关注</label>
  14. <label class='info-items'>{{receiveLikeCounts}} 获赞</label>
  15. </view>
  16. </view>
  17.  
  18. </view>
  19.  
  20. <view class="line"></view>

mine.wxml

  1. var videoUtil = require('../../utils/videoUtil.js')
  2.  
  3. const app = getApp()
  4.  
  5. Page({
  6. data: {
  7. faceUrl: "../resource/images/noneface.png",
  8. },
  9.  
  10. onLoad: function (params) {
  11. var me = this;
  12. var user = app.userInfo;
  13. wx.showLoading({
  14. title: '请等待...',
  15. });
  16. // 调用后端
  17. var serverUrl = app.serverUrl;
  18. wx.request({
  19. url: serverUrl + '/user/query?userId='+user.id,
  20. method: "POST",
  21. header: {
  22. 'content-type': 'application/json' // 默认值
  23. },
  24. success: function (res) {
  25. console.log(res.data);
  26. wx.hideLoading();
  27. if (res.data.status == 200) {
  28. var userInfo= res.data.data;
  29. var faceUrl = "../resource/images/noneface.png";
  30. if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){
  31. faceUrl = serverUrl + userInfo.faceImage;
  32. }
  33.  
  34. me.setData({
  35. faceUrl: faceUrl,
  36. fansCounts: userInfo.fansCounts,
  37. followCounts: userInfo.followCounts,
  38. receiveLikeCounts: userInfo.receiveLikeCounts,
  39. nickname: userInfo.nickname
  40. });
  41. }
  42. }
  43. })
  44. },
  45.  
  46. logout:function(params){
  47. var user = app.userInfo;
  48. var serverUrl = app.serverUrl;
  49. wx.showLoading({
  50. title: '请等待...',
  51. });
  52. // 调用后端
  53. wx.request({
  54. url: serverUrl + '/logout?userId='+user.id,
  55. method: "POST",
  56. header: {
  57. 'content-type': 'application/json' // 默认值
  58. },
  59. success: function (res) {
  60. console.log(res.data);
  61. wx.hideLoading();
  62. if (res.data.status == 200) {
  63. // 注销成功
  64. wx.showToast({
  65. title: '注销成功',
  66. icon: 'success',
  67. duration: 2000
  68. });
  69. //清除全局用户对象
  70. app.userInfo = null;
  71. //页面跳转
  72. wx.navigateTo({
  73. url: '../userLogin/login',
  74. })
  75. }
  76. }
  77. })
  78. },
  79.  
  80. changeFace:function(){
  81. var me = this;
  82. wx.chooseImage({
  83. count: 1,
  84. sizeType: ['compressed'],
  85. sourceType: ['album'],
  86. success:function(res) {
  87. var tempFilePaths = res.tempFilePaths;
  88. console.log(tempFilePaths);
  89.  
  90. wx.showLoading({
  91. title: '上传中...',
  92. })
  93.  
  94. var serverUrl = app.serverUrl;
  95. wx.uploadFile({
  96. url: serverUrl+'/user/uploadFace?userId='+app.userInfo.id,
  97. filePath: tempFilePaths[0],
  98. name: 'file',
  99. header: {
  100. 'content-type': 'application/json' // 默认值
  101. },
  102. success: function (res) {
  103. var data = JSON.parse(res.data);
  104. console.log(data);
  105. wx.hideLoading();
  106. if(data.status == 200){
  107. wx.showToast({
  108. title: '上传成功',
  109. icon: "success"
  110. });
  111.  
  112. var imageUrl = data.data;
  113. me.setData({
  114. faceUrl: serverUrl+imageUrl
  115. });
  116.  
  117. } else if (data.status == 500){
  118. wx.showToast({
  119. title: data.msg
  120. });
  121. }
  122. }
  123. })
  124.  
  125. }
  126. })
  127. },
  128.  
  129. uploadVideo:function(){
  130. var me =this;
  131. wx.chooseVideo({
  132. sourceType: ['album'],
  133. success(res) {
  134. console.log(res);
  135. }
  136. })
  137. }
  138.  
  139. })

mine.js

背景BGM音乐

  选择背景音乐页面

  1. <view>
  2. <form bindsubmit='upload'>
  3.  
  4. <view class="inputView">
  5. <label class="loginLabel">视频描述:</label>
  6. <input name="desc" class="inputText" placeholder="说点什么吧" />
  7. </view>
  8.  
  9. <!-- 提交 -->
  10. <button class="submitBtn" type="primary" form-type='submit'>上传视频</button>
  11.  
  12. <button class="gobackBtn" type="warn" form-type='reset'>重置</button>
  13. </form>
  14. </view>

chooseBgm.wxml

  1. const app = getApp()
  2.  
  3. Page({
  4. data: {
  5.  
  6. },
  7.  
  8. onLoad: function (params) {
  9. },
  10.  
  11. })

chooseBgm.js

  添加音乐模块样式

  1. <radio-group name="bgm">
  2.  
  3. <view class='container'>
  4. <audio poster="{{poster}}" name="{{name}}" author="{{author}}" src="{{src}}" id="myAudio" controls loop></audio>
  5. <radio style='margin-top:20px;' value=''></radio>
  6. </view>
  7.  
  8. </radio-group>

  1. <view>
  2. <form bindsubmit='upload'>
  3.  
  4. <radio-group name="bgm">
  5.  
  6. <view class='container'>
  7. <audio poster="{{poster}}" name="{{name}}" author="{{author}}" src="{{src}}" id="myAudio" controls loop></audio>
  8. <radio style='margin-top:20px;' value=''></radio>
  9. </view>
  10.  
  11. </radio-group>
  12.  
  13. <view class="inputView">
  14. <label class="loginLabel">视频描述:</label>
  15. <input name="desc" class="inputText" placeholder="说点什么吧" />
  16. </view>
  17.  
  18. <!-- 提交 -->
  19. <button class="submitBtn" type="primary" form-type='submit'>上传视频</button>
  20.  
  21. <button class="gobackBtn" type="warn" form-type='reset'>重置</button>
  22. </form>
  23. </view>

chooseBgm.wxml

  1. const app = getApp()
  2.  
  3. Page({
  4. data: {
  5. poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
  6. name: '此时此刻',
  7. author: '许巍',
  8. src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
  9. },
  10.  
  11. onLoad: function (params) {
  12. },
  13.  
  14. })

chooseBgm.js

  数据库中单独添加一条数据

  

  音乐文件放在虚拟路径F:\imooc-video-gary\bgm下

  

  添加查询Bgm的Controller层

  1. @RestController
  2. @Api(value="背景音乐业务的接口",tags= {"背景音乐业务的controller"})
  3. @RequestMapping("/bgm")
  4. public class BgmController {
  5.  
  6. @Autowired
  7. private BgmService bgmService;
  8.  
  9. @ApiOperation(value="获取背景音乐列表",notes="获取背景音乐列表的接口")
  10. @PostMapping("/list")
  11. public IMoocJSONResult list() {
  12. return IMoocJSONResult.ok(bgmService.queryBgmList());
  13. }
  14.  
  15. }

  添加查询Bgm的Service

  1. @Transactional(propagation = Propagation.SUPPORTS)
  2. @Override
  3. public List<Bgm> queryBgmList() {
  4.  
  5. return bgmMapper.selectAll();
  6. }

  

  1. package com.imooc.controller;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.PostMapping;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7.  
  8. import com.imooc.service.BgmService;
  9. import com.imooc.utils.IMoocJSONResult;
  10.  
  11. import io.swagger.annotations.Api;
  12. import io.swagger.annotations.ApiOperation;
  13.  
  14. @RestController
  15. @Api(value="背景音乐业务的接口",tags= {"背景音乐业务的controller"})
  16. @RequestMapping("/bgm")
  17. public class BgmController {
  18.  
  19. @Autowired
  20. private BgmService bgmService;
  21.  
  22. @ApiOperation(value="获取背景音乐列表",notes="获取背景音乐列表的接口")
  23. @PostMapping("/list")
  24. public IMoocJSONResult list() {
  25. return IMoocJSONResult.ok(bgmService.queryBgmList());
  26. }
  27.  
  28. }

BgmController.java

  1. package com.imooc.service;
  2.  
  3. import java.util.List;
  4.  
  5. import com.imooc.pojo.Bgm;
  6. import com.imooc.pojo.Users;
  7.  
  8. public interface BgmService {
  9.  
  10. //查询背景音乐列表
  11. public List<Bgm> queryBgmList();
  12.  
  13. }

BgmService.java

  1. package com.imooc.server.impl;
  2.  
  3. import java.util.List;
  4.  
  5. import org.n3r.idworker.Sid;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.transaction.annotation.Propagation;
  9. import org.springframework.transaction.annotation.Transactional;
  10.  
  11. import com.imooc.mapper.BgmMapper;
  12. import com.imooc.mapper.UsersMapper;
  13. import com.imooc.pojo.Bgm;
  14. import com.imooc.pojo.Users;
  15. import com.imooc.service.BgmService;
  16. import com.imooc.service.UserService;
  17.  
  18. import tk.mybatis.mapper.entity.Example;
  19. import tk.mybatis.mapper.entity.Example.Criteria;
  20.  
  21. @Service
  22. public class BgmServiceImpl implements BgmService {
  23.  
  24. @Autowired
  25. private BgmMapper bgmMapper;
  26.  
  27. @Autowired
  28. private Sid sid;
  29.  
  30. @Transactional(propagation = Propagation.SUPPORTS)
  31. @Override
  32. public List<Bgm> queryBgmList() {
  33.  
  34. return bgmMapper.selectAll();
  35. }
  36.  
  37. }

BgmServiceImpl.java

 微信小程序bgm页面联调获取背景音乐列表

  chooseBgm.wxml中通过使用block循环获得数据库中的bgm

  1. <block wx:for="{{bgmList}}">
  2. <view class='container'>
  3. <audio name="{{item.name}}" author="{{item.author}}" src="{{serverUrl}}{{item.path}}" id="myAudio" controls loop></audio>
  4. <radio style='margin-top:20px;' value='{{item.id}}'></radio>
  5. </view>
  6. </block>

  为防止用户歌曲名字输入时过长,可以在<audio>组件中通过style='width:300px'去进行歌曲名长度控制

  1. <audio name="{{item.name}}" author="{{item.author}}" src="{{serverUrl}}{{item.path}}" style='width:300px' id="myAudio" controls loop></audio>

  chooseBgm.js中通过编写onLoad函数去对后台发起bgm/list请求

  1. onLoad: function (params) {
  2. var me = this;
  3.  
  4. wx.showLoading({
  5. title: '请等待...',
  6. });
  7. // 调用后端
  8. var serverUrl = app.serverUrl;
  9. wx.request({
  10. url: serverUrl + '/bgm/list',
  11. method: "POST",
  12. header: {
  13. 'content-type': 'application/json' // 默认值
  14. },
  15. success: function (res) {
  16. console.log(res.data);
  17. wx.hideLoading();
  18. if (res.data.status == 200) {
  19. var bgmList = res.data.data;
  20. me.setData({
  21. bgmList:bgmList,
  22. serverUrl: serverUrl
  23. });
  24. }
  25. }
  26. })
  27.  
  28. },

  1. <view>
  2. <form bindsubmit='upload'>
  3.  
  4. <radio-group name="bgm">
  5.  
  6. <block wx:for="{{bgmList}}">
  7. <view class='container'>
  8. <audio name="{{item.name}}" author="{{item.author}}" src="{{serverUrl}}{{item.path}}" style='width:300px' id="myAudio" controls loop></audio>
  9. <radio style='margin-top:20px;' value='{{item.id}}'></radio>
  10. </view>
  11. </block>
  12. </radio-group>
  13.  
  14. <view class="inputView">
  15. <label class="loginLabel">视频描述:</label>
  16. <input name="desc" class="inputText" placeholder="说点什么吧" />
  17. </view>
  18.  
  19. <!-- 提交 -->
  20. <button class="submitBtn" type="primary" form-type='submit'>上传视频</button>
  21.  
  22. <button class="gobackBtn" type="warn" form-type='reset'>重置</button>
  23. </form>
  24. </view>

chooseBgm.wxml

  1. const app = getApp()
  2.  
  3. Page({
  4. data: {
  5. bgmList:[],
  6. serverUrl:"",
  7. poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
  8. name: '此时此刻',
  9. author: '许巍',
  10. src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
  11. },
  12.  
  13. onLoad: function (params) {
  14. var me = this;
  15.  
  16. wx.showLoading({
  17. title: '请等待...',
  18. });
  19. // 调用后端
  20. var serverUrl = app.serverUrl;
  21. wx.request({
  22. url: serverUrl + '/bgm/list',
  23. method: "POST",
  24. header: {
  25. 'content-type': 'application/json' // 默认值
  26. },
  27. success: function (res) {
  28. console.log(res.data);
  29. wx.hideLoading();
  30. if (res.data.status == 200) {
  31. var bgmList = res.data.data;
  32. me.setData({
  33. bgmList:bgmList,
  34. serverUrl: serverUrl
  35. });
  36. }
  37. }
  38. })
  39.  
  40. },
  41.  
  42. })

chooseBgm.js

 开发上传短视频接口

  短视频上传接口类似上传头像

  1. @PostMapping(value="/upload",headers="content-type=multipart/form-data")
  2. public IMoocJSONResult uploadFace(String userId,
  3. String bgmId,double videoSeconds,int videoWidth,int videoHeight,String desc,
  4. @ApiParam(value="短视频",required=true)
  5. MultipartFile file) throws Exception {
  6.  
  7. if(StringUtils.isBlank(userId)) {
  8. return IMoocJSONResult.errorMsg("用户id不能为空...");
  9. }
  10.  
  11. //文件保存命名空间
  12. String fileSpace = "F:/imooc-video-gary";
  13. //保存到数据库中的相对路径
  14. String uploadPathDB = "/" + userId + "/video";
  15.  
  16. FileOutputStream fileOutputStream = null;
  17. InputStream inputStream = null;
  18.  
  19. try {
  20. if( file != null ) {
  21.  
  22. String fileName = file.getOriginalFilename();
  23. if(StringUtils.isNoneBlank(fileName)) {
  24. //文件上传的最终保存路径
  25. String finalVideoPath = fileSpace + uploadPathDB + "/" + fileName;
  26. //设置数据库保存的路径
  27. uploadPathDB += ("/" + fileName);
  28.  
  29. File outFile = new File(finalVideoPath);
  30. if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
  31. //创建父文件夹
  32. outFile.getParentFile().mkdirs();
  33. }
  34.  
  35. fileOutputStream = new FileOutputStream(outFile);
  36. inputStream = file.getInputStream();
  37. IOUtils.copy(inputStream, fileOutputStream);
  38. }
  39.  
  40. }else {
  41. return IMoocJSONResult.errorMsg("上传出错...");
  42. }
  43. } catch (Exception e) {
  44. // TODO Auto-generated catch block
  45. e.printStackTrace();
  46. return IMoocJSONResult.errorMsg("上传出错...");
  47. }finally {
  48. if(fileOutputStream != null) {
  49. fileOutputStream.flush();
  50. fileOutputStream.close();
  51. }
  52. }
  53.  
  54. return IMoocJSONResult.ok();
  55. }

  1. package com.imooc.controller;
  2.  
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.InputStream;
  6.  
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.apache.tomcat.util.http.fileupload.IOUtils;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestParam;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import org.springframework.web.multipart.MultipartFile;
  14.  
  15. import com.imooc.pojo.Users;
  16. import com.imooc.utils.IMoocJSONResult;
  17.  
  18. import io.swagger.annotations.Api;
  19. import io.swagger.annotations.ApiImplicitParam;
  20. import io.swagger.annotations.ApiImplicitParams;
  21. import io.swagger.annotations.ApiOperation;
  22. import io.swagger.annotations.ApiParam;
  23.  
  24. @RestController
  25. @Api(value="视频相关业务的接口",tags= {"视频相关业务的controller"})
  26. @RequestMapping("/video")
  27. public class VideoController {
  28.  
  29. @ApiOperation(value="用户视频", notes="上传视频的接口")
  30. @ApiImplicitParams({
  31. @ApiImplicitParam(name="userId",value="用户id",required=true,
  32. dataType="String" ,paramType="query"),
  33. @ApiImplicitParam(name="bgmId",value="背景音乐id",required=false,
  34. dataType="String" ,paramType="query"),
  35. @ApiImplicitParam(name="videoSeconds",value="背景音乐播放长度",required=true,
  36. dataType="String" ,paramType="query"),
  37. @ApiImplicitParam(name="videoWidth",value="视频的宽度",required=true,
  38. dataType="String" ,paramType="query"),
  39. @ApiImplicitParam(name="videoHeight",value="视频的高度",required=true,
  40. dataType="String" ,paramType="query"),
  41. @ApiImplicitParam(name="desc",value="视频的描述",required=false,
  42. dataType="String" ,paramType="query")
  43. })
  44.  
  45. @PostMapping(value="/upload",headers="content-type=multipart/form-data")
  46. public IMoocJSONResult uploadFace(String userId,
  47. String bgmId,double videoSeconds,int videoWidth,int videoHeight,String desc,
  48. @ApiParam(value="短视频",required=true)
  49. MultipartFile file) throws Exception {
  50.  
  51. if(StringUtils.isBlank(userId)) {
  52. return IMoocJSONResult.errorMsg("用户id不能为空...");
  53. }
  54.  
  55. //文件保存命名空间
  56. String fileSpace = "F:/imooc-video-gary";
  57. //保存到数据库中的相对路径
  58. String uploadPathDB = "/" + userId + "/video";
  59.  
  60. FileOutputStream fileOutputStream = null;
  61. InputStream inputStream = null;
  62.  
  63. try {
  64. if( file != null ) {
  65.  
  66. String fileName = file.getOriginalFilename();
  67. if(StringUtils.isNoneBlank(fileName)) {
  68. //文件上传的最终保存路径
  69. String finalVideoPath = fileSpace + uploadPathDB + "/" + fileName;
  70. //设置数据库保存的路径
  71. uploadPathDB += ("/" + fileName);
  72.  
  73. File outFile = new File(finalVideoPath);
  74. if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
  75. //创建父文件夹
  76. outFile.getParentFile().mkdirs();
  77. }
  78.  
  79. fileOutputStream = new FileOutputStream(outFile);
  80. inputStream = file.getInputStream();
  81. IOUtils.copy(inputStream, fileOutputStream);
  82. }
  83.  
  84. }else {
  85. return IMoocJSONResult.errorMsg("上传出错...");
  86. }
  87. } catch (Exception e) {
  88. // TODO Auto-generated catch block
  89. e.printStackTrace();
  90. return IMoocJSONResult.errorMsg("上传出错...");
  91. }finally {
  92. if(fileOutputStream != null) {
  93. fileOutputStream.flush();
  94. fileOutputStream.close();
  95. }
  96. }
  97.  
  98. return IMoocJSONResult.ok();
  99. }
  100.  
  101. }

VideoController.java

  小程序上传视频

  视频从mine页面传参到chooseBgm页面

  1. uploadVideo:function(){
  2. var me =this;
  3. wx.chooseVideo({
  4. sourceType: ['album'],
  5. success(res) {
  6. console.log(res);
  7.  
  8. var duration = res.duration;
  9. var tmpheight = res.height;
  10. var tmpwidth = res.width;
  11. var tmpVideoUrl = res.tempFilePath;
  12. var tmpCoverUrl = res.thumbTempFilePath;
  13.  
  14. if(duration>300){
  15. wx.showToast({
  16. title: '视频长度不能超过5分钟...',
  17. icon:"none",
  18. duration:2500
  19. })
  20. } else if(duration<3){
  21. wx.showToast({
  22. title: '视频长度太短,请上传超过3秒的视频...',
  23. icon: "none",
  24. duration: 2500
  25. })
  26. }else{
  27. //打开选择bgm页面
  28. wx.navigateTo({
  29. url: '../chooseBgm/chooseBgm?duration=' + duration
  30. + "&tmpheight=" + tmpheight
  31. + "&tmpwidth=" + tmpwidth
  32. + "&tmpVideoUrl=" + tmpVideoUrl
  33. + "&tmpCoverUrl=" + tmpCoverUrl
  34. ,
  35. })
  36. }
  37.  
  38. }
  39. })
  40. }

  chooseBgm页面通过upload函数将视频上传缓存到本地

  1. upload:function(e){
  2. var me = this;
  3.  
  4. var bgmId = e.detail.value.bgmId;
  5. var desc = e.detail.value.desc;
  6.  
  7. console.log("bgmId:"+ bgmId);
  8. console.log("desc:" + desc);
  9.  
  10. var duration = me.data.videoParams.duration;
  11. var tmpheight = me.data.videoParams.tmpheight;
  12. var tmpwidth = me.data.videoParams.tmpwidth;
  13. var tmpVideoUrl = me.data.videoParams.tmpVideoUrl;
  14. var tmpCoverUrl = me.data.videoParams.tmpCoverUrl;
  15.  
  16. //上传短视频
  17. wx.showLoading({
  18. title: '上传中...',
  19. })
  20.  
  21. var serverUrl = app.serverUrl;
  22. wx.uploadFile({
  23. url: serverUrl + '/video/upload',
  24. formData:{
  25. userId: app.userInfo.id,
  26. bgmId:bgmId,
  27. desc: desc,
  28. videoSeconds: duration,
  29. videoWidth: tmpheight,
  30. videoHeight: tmpwidth,
  31. },
  32. filePath: tmpVideoUrl,
  33. name: 'file',
  34. header: {
  35. 'content-type': 'application/json' // 默认值
  36. },
  37. success: function (res) {
  38. var data = JSON.parse(res.data);
  39. console.log(res);
  40. wx.hideLoading();
  41. if (data.status == 200) {
  42. wx.showToast({
  43. title: '上传成功',
  44. icon: "success"
  45. });
  46. }
  47. }
  48. })
  49.  
  50. }

  1. <view>
  2. <form bindsubmit='upload'>
  3.  
  4. <radio-group name="bgmId">
  5.  
  6. <block wx:for="{{bgmList}}" wx:key="">
  7. <view class='container'>
  8. <audio name="{{item.name}}" author="{{item.author}}" src="{{serverUrl}}{{item.path}}" style='width:300px' id="myAudio" controls loop></audio>
  9. <radio style='margin-top:20px;' value='{{item.id}}'></radio>
  10. </view>
  11. </block>
  12. </radio-group>
  13.  
  14. <view class="inputView">
  15. <label class="loginLabel">视频描述:</label>
  16. <input name="desc" class="inputText" placeholder="说点什么吧" />
  17. </view>
  18.  
  19. <!-- 提交 -->
  20. <button class="submitBtn" type="primary" form-type='submit'>上传视频</button>
  21.  
  22. <button class="gobackBtn" type="warn" form-type='reset'>重置</button>
  23. </form>
  24. </view>

chooseBgm.xml

  1. const app = getApp()
  2.  
  3. Page({
  4. data: {
  5. bgmList:[],
  6. serverUrl:"",
  7. videoParams:{}
  8. },
  9.  
  10. onLoad: function (params) {
  11. var me = this;
  12. console.log(params);
  13. me.setData({
  14. videoParams: params
  15. });
  16.  
  17. wx.showLoading({
  18. title: '请等待...',
  19. });
  20. // 调用后端
  21. var serverUrl = app.serverUrl;
  22. wx.request({
  23. url: serverUrl + '/bgm/list',
  24. method: "POST",
  25. header: {
  26. 'content-type': 'application/json' // 默认值
  27. },
  28. success: function (res) {
  29. console.log(res.data);
  30. wx.hideLoading();
  31. if (res.data.status == 200) {
  32. var bgmList = res.data.data;
  33. me.setData({
  34. bgmList:bgmList,
  35. serverUrl: serverUrl
  36. });
  37. }
  38. }
  39. })
  40.  
  41. },
  42.  
  43. upload:function(e){
  44. var me = this;
  45.  
  46. var bgmId = e.detail.value.bgmId;
  47. var desc = e.detail.value.desc;
  48.  
  49. console.log("bgmId:"+ bgmId);
  50. console.log("desc:" + desc);
  51.  
  52. var duration = me.data.videoParams.duration;
  53. var tmpheight = me.data.videoParams.tmpheight;
  54. var tmpwidth = me.data.videoParams.tmpwidth;
  55. var tmpVideoUrl = me.data.videoParams.tmpVideoUrl;
  56. var tmpCoverUrl = me.data.videoParams.tmpCoverUrl;
  57.  
  58. //上传短视频
  59. wx.showLoading({
  60. title: '上传中...',
  61. })
  62.  
  63. var serverUrl = app.serverUrl;
  64. wx.uploadFile({
  65. url: serverUrl + '/video/upload',
  66. formData:{
  67. userId: app.userInfo.id,
  68. bgmId:bgmId,
  69. desc: desc,
  70. videoSeconds: duration,
  71. videoWidth: tmpheight,
  72. videoHeight: tmpwidth,
  73. },
  74. filePath: tmpVideoUrl,
  75. name: 'file',
  76. header: {
  77. 'content-type': 'application/json' // 默认值
  78. },
  79. success: function (res) {
  80. var data = JSON.parse(res.data);
  81. console.log(res);
  82. wx.hideLoading();
  83. if (data.status == 200) {
  84. wx.showToast({
  85. title: '上传成功',
  86. icon: "success"
  87. });
  88. }
  89. }
  90. })
  91.  
  92. }
  93.  
  94. })

chooseBgm.js

  1. var videoUtil = require('../../utils/videoUtil.js')
  2.  
  3. const app = getApp()
  4.  
  5. Page({
  6. data: {
  7. faceUrl: "../resource/images/noneface.png",
  8. },
  9.  
  10. onLoad: function (params) {
  11. var me = this;
  12. var user = app.userInfo;
  13. wx.showLoading({
  14. title: '请等待...',
  15. });
  16. // 调用后端
  17. var serverUrl = app.serverUrl;
  18. wx.request({
  19. url: serverUrl + '/user/query?userId='+user.id,
  20. method: "POST",
  21. header: {
  22. 'content-type': 'application/json' // 默认值
  23. },
  24. success: function (res) {
  25. console.log(res.data);
  26. wx.hideLoading();
  27. if (res.data.status == 200) {
  28. var userInfo= res.data.data;
  29. var faceUrl = "../resource/images/noneface.png";
  30. if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){
  31. faceUrl = serverUrl + userInfo.faceImage;
  32. }
  33.  
  34. me.setData({
  35. faceUrl: faceUrl,
  36. fansCounts: userInfo.fansCounts,
  37. followCounts: userInfo.followCounts,
  38. receiveLikeCounts: userInfo.receiveLikeCounts,
  39. nickname: userInfo.nickname
  40. });
  41. }
  42. }
  43. })
  44. },
  45.  
  46. logout:function(params){
  47. var user = app.userInfo;
  48. var serverUrl = app.serverUrl;
  49. wx.showLoading({
  50. title: '请等待...',
  51. });
  52. // 调用后端
  53. wx.request({
  54. url: serverUrl + '/logout?userId='+user.id,
  55. method: "POST",
  56. header: {
  57. 'content-type': 'application/json' // 默认值
  58. },
  59. success: function (res) {
  60. console.log(res.data);
  61. wx.hideLoading();
  62. if (res.data.status == 200) {
  63. // 注销成功
  64. wx.showToast({
  65. title: '注销成功',
  66. icon: 'success',
  67. duration: 2000
  68. });
  69. //清除全局用户对象
  70. app.userInfo = null;
  71. //页面跳转
  72. wx.navigateTo({
  73. url: '../userLogin/login',
  74. })
  75. }
  76. }
  77. })
  78. },
  79.  
  80. changeFace:function(){
  81. var me = this;
  82. wx.chooseImage({
  83. count: 1,
  84. sizeType: ['compressed'],
  85. sourceType: ['album'],
  86. success:function(res) {
  87. var tempFilePaths = res.tempFilePaths;
  88. console.log(tempFilePaths);
  89.  
  90. wx.showLoading({
  91. title: '上传中...',
  92. })
  93.  
  94. var serverUrl = app.serverUrl;
  95. wx.uploadFile({
  96. url: serverUrl+'/user/uploadFace?userId='+app.userInfo.id,
  97. filePath: tempFilePaths[0],
  98. name: 'file',
  99. header: {
  100. 'content-type': 'application/json' // 默认值
  101. },
  102. success: function (res) {
  103. var data = JSON.parse(res.data);
  104. console.log(data);
  105. wx.hideLoading();
  106. if(data.status == 200){
  107. wx.showToast({
  108. title: '上传成功',
  109. icon: "success"
  110. });
  111.  
  112. var imageUrl = data.data;
  113. me.setData({
  114. faceUrl: serverUrl+imageUrl
  115. });
  116.  
  117. } else if (data.status == 500){
  118. wx.showToast({
  119. title: data.msg
  120. });
  121. }
  122. }
  123. })
  124.  
  125. }
  126. })
  127. },
  128.  
  129. uploadVideo:function(){
  130. var me =this;
  131. wx.chooseVideo({
  132. sourceType: ['album'],
  133. success(res) {
  134. console.log(res);
  135.  
  136. var duration = res.duration;
  137. var tmpheight = res.height;
  138. var tmpwidth = res.width;
  139. var tmpVideoUrl = res.tempFilePath;
  140. var tmpCoverUrl = res.thumbTempFilePath;
  141.  
  142. if(duration>300){
  143. wx.showToast({
  144. title: '视频长度不能超过5分钟...',
  145. icon:"none",
  146. duration:2500
  147. })
  148. } else if(duration<3){
  149. wx.showToast({
  150. title: '视频长度太短,请上传超过3秒的视频...',
  151. icon: "none",
  152. duration: 2500
  153. })
  154. }else{
  155. //打开选择bgm页面
  156. wx.navigateTo({
  157. url: '../chooseBgm/chooseBgm?duration=' + duration
  158. + "&tmpheight=" + tmpheight
  159. + "&tmpwidth=" + tmpwidth
  160. + "&tmpVideoUrl=" + tmpVideoUrl
  161. + "&tmpCoverUrl=" + tmpCoverUrl
  162. ,
  163. })
  164. }
  165.  
  166. }
  167. })
  168. }
  169.  
  170. })

mine.js

ffmpeg

  ffmpeg:视音频处理工具,跨平台的视音频处理解决方案

  视频转换命令

  1. $ ffmpeg -i input.mp4 output.avi

  

Java于ffmpeg的结合

  在common层中创建FFMpegTest.java类,实现java于ffmpeg的结合

  1. package com.imooc.utils;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class FFMpegTest {
  7.  
  8. private String ffmpegEXE;
  9.  
  10. public FFMpegTest(String ffmpegEXE) {
  11. super();
  12. this.ffmpegEXE = ffmpegEXE;
  13. }
  14.  
  15. public void convertor(String videoInputPath,String videoOutputPath) throws Exception{
  16. //$ ffmpeg -i input.mp4 output.avi
  17. List<String> command = new ArrayList<>();
  18. command.add(ffmpegEXE);
  19. command.add("-i");
  20. command.add(videoInputPath);
  21. command.add(videoOutputPath);
  22.  
  23. for(String c:command) {
  24. System.out.print(c);
  25. }
  26.  
  27. ProcessBuilder process = new ProcessBuilder(command);
  28. process.start();
  29. }
  30.  
  31. public static void main(String[] args) {
  32. FFMpegTest ffmpeg = new FFMpegTest("F:\\Garyffmpeg\\ffmpeg\\bin\\ffmpeg.exe");
  33. try {
  34. ffmpeg.convertor("E:\\19222\\毕业生.mp4","E:\\19222\\毕.avi");
  35. } catch (Exception e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. }
  39. }
  40.  
  41. }

FFMpegTest.java

  可以看到转码格式的输出

  为了提高资源的利用率,可以在convertor()方法中提高流资源利用率

  1. public void convertor(String videoInputPath,String videoOutputPath) throws Exception{
  2. //$ ffmpeg -i input.mp4 output.avi
  3. List<String> command = new ArrayList<>();
  4. command.add(ffmpegEXE);
  5. command.add("-i");
  6. command.add(videoInputPath);
  7. command.add(videoOutputPath);
  8.  
  9. for(String c:command) {
  10. System.out.print(c);
  11. }
  12.  
  13. ProcessBuilder builder = new ProcessBuilder(command);
  14. Process process = builder.start();
  15.  
  16. InputStream errorStream = process.getErrorStream();
  17. InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
  18. BufferedReader br = new BufferedReader(inputStreamReader);
  19.  
  20. String line = "";
  21. //一直读取到最后一行
  22. while((line=br.readLine()) !=null ) {
  23. }
  24.  
  25. if(br!=null) {
  26. br.close();
  27. }
  28.  
  29. if(inputStreamReader!=null) {
  30. inputStreamReader.close();
  31. }
  32.  
  33. if(errorStream!=null) {
  34. errorStream.close();
  35. }
  36.  
  37. }
  1. package com.imooc.utils;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. public class FFMpegTest {
  10.  
  11. private String ffmpegEXE;
  12.  
  13. public FFMpegTest(String ffmpegEXE) {
  14. super();
  15. this.ffmpegEXE = ffmpegEXE;
  16. }
  17.  
  18. public void convertor(String videoInputPath,String videoOutputPath) throws Exception{
  19. //$ ffmpeg -i input.mp4 output.avi
  20. List<String> command = new ArrayList<>();
  21. command.add(ffmpegEXE);
  22. command.add("-i");
  23. command.add(videoInputPath);
  24. command.add(videoOutputPath);
  25.  
  26. for(String c:command) {
  27. System.out.print(c);
  28. }
  29.  
  30. ProcessBuilder builder = new ProcessBuilder(command);
  31. Process process = builder.start();
  32.  
  33. InputStream errorStream = process.getErrorStream();
  34. InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
  35. BufferedReader br = new BufferedReader(inputStreamReader);
  36.  
  37. String line = "";
  38. //一直读取到最后一行
  39. while((line=br.readLine()) !=null ) {
  40. }
  41.  
  42. if(br!=null) {
  43. br.close();
  44. }
  45.  
  46. if(inputStreamReader!=null) {
  47. inputStreamReader.close();
  48. }
  49.  
  50. if(errorStream!=null) {
  51. errorStream.close();
  52. }
  53.  
  54. }
  55.  
  56. public static void main(String[] args) {
  57. FFMpegTest ffmpeg = new FFMpegTest("F:\\Garyffmpeg\\ffmpeg\\bin\\ffmpeg.exe");
  58. try {
  59. ffmpeg.convertor("E:\\19222\\毕业生.mp4","E:\\19222\\毕2.avi");
  60. } catch (Exception e) {
  61. // TODO Auto-generated catch block
  62. e.printStackTrace();
  63. }
  64. }
  65.  
  66. }

FFMpegTest.java

ffmpeg操作视频与bgm结合

  视频与bgm结合,最终长度以视频的为主

  Gary.mp4视频与GaryMusic.mp3音频合成,合成新的new.mp4文件

  

  同理使用java代码生成mp4视频

  1. public void convertor(String videoInputPath,String mp3InputPath,
  2. double seconds,String videoOutputPath) throws Exception{
  3. //ffmpeg.exe -i Gary.mp4 -i GaryMusic.mp3 -t 7 -y new.mp4
  4. List<String> command = new ArrayList<>();
  5. command.add(ffmpegEXE);
  6.  
  7. command.add("-i");
  8. command.add(videoInputPath);
  9.  
  10. command.add("-i");
  11. command.add(mp3InputPath);
  12.  
  13. command.add("-t");
  14. command.add(String.valueOf(seconds));
  15.  
  16. command.add("-y");
  17. command.add(videoOutputPath);
  18.  
  19. for(String c:command) {
  20. System.out.print(c);
  21. }
  22.  
  23. ProcessBuilder builder = new ProcessBuilder(command);
  24. Process process = builder.start();
  25.  
  26. InputStream errorStream = process.getErrorStream();
  27. InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
  28. BufferedReader br = new BufferedReader(inputStreamReader);
  29.  
  30. String line = "";
  31. //一直读取到最后一行
  32. while((line=br.readLine()) !=null ) {
  33. }
  34.  
  35. if(br!=null) {
  36. br.close();
  37. }
  38.  
  39. if(inputStreamReader!=null) {
  40. inputStreamReader.close();
  41. }
  42.  
  43. if(errorStream!=null) {
  44. errorStream.close();
  45. }
  46.  
  47. }
  1. package com.imooc.utils;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. public class MergeVideoMp3 {
  10.  
  11. private String ffmpegEXE;
  12.  
  13. public MergeVideoMp3(String ffmpegEXE) {
  14. super();
  15. this.ffmpegEXE = ffmpegEXE;
  16. }
  17.  
  18. public void convertor(String videoInputPath,String mp3InputPath,
  19. double seconds,String videoOutputPath) throws Exception{
  20. //ffmpeg.exe -i Gary.mp4 -i GaryMusic.mp3 -t 7 -y new.mp4
  21. List<String> command = new ArrayList<>();
  22. command.add(ffmpegEXE);
  23.  
  24. command.add("-i");
  25. command.add(videoInputPath);
  26.  
  27. command.add("-i");
  28. command.add(mp3InputPath);
  29.  
  30. command.add("-t");
  31. command.add(String.valueOf(seconds));
  32.  
  33. command.add("-y");
  34. command.add(videoOutputPath);
  35.  
  36. for(String c:command) {
  37. System.out.print(c);
  38. }
  39.  
  40. ProcessBuilder builder = new ProcessBuilder(command);
  41. Process process = builder.start();
  42.  
  43. InputStream errorStream = process.getErrorStream();
  44. InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
  45. BufferedReader br = new BufferedReader(inputStreamReader);
  46.  
  47. String line = "";
  48. //一直读取到最后一行
  49. while((line=br.readLine()) !=null ) {
  50. }
  51.  
  52. if(br!=null) {
  53. br.close();
  54. }
  55.  
  56. if(inputStreamReader!=null) {
  57. inputStreamReader.close();
  58. }
  59.  
  60. if(errorStream!=null) {
  61. errorStream.close();
  62. }
  63.  
  64. }
  65.  
  66. public static void main(String[] args) {
  67. MergeVideoMp3 ffmpeg = new MergeVideoMp3("F:\\Garyffmpeg\\ffmpeg\\bin\\ffmpeg.exe");
  68. try {
  69. ffmpeg.convertor("E:\\19222\\毕业生.mp4","E:\\19222\\GaryMusic.mp3",7.1,"E:\\19222\\通过java生成的视频.mp4");
  70. } catch (Exception e) {
  71. // TODO Auto-generated catch block
  72. e.printStackTrace();
  73. }
  74. }
  75.  
  76. }

MergeVideoMp3.java

 小程序上传视频后调用视频处理工具类联调

  可以在小程序端添加判断用户是否选择了BGM,如果不用户选择合成BGM,那就查询bgm的信息,并且合并视频生成新的视频

  1. if(StringUtils.isNotBlank(bgmId)) {
  2. Bgm bgm = bgmService.queryBgmById(bgmId);
  3. String mp3InputPath = FILE_SPACE + bgm.getPath();
  4. //System.out.println("1:mp3InputPath + "+mp3InputPath);
  5. MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE);
  6. String videoInputPath = finalVideoPath;
  7.  
  8. String videdoOutputName = UUID.randomUUID().toString() + ".mp4";
  9. uploadPathDB = "/" + userId + "/video" + "/" +videdoOutputName;
  10. finalVideoPath = FILE_SPACE + uploadPathDB;
  11. tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
  12.  
  13. }

  FFMpegTest.java作为FFMpeg合并短视频的BGM

  1. public void convertor(String videoInputPath,String videoOutputPath) throws Exception{
  2. //$ ffmpeg -i input.mp4 output.avi
  3. List<String> command = new ArrayList<>();
  4. command.add(ffmpegEXE);
  5. command.add("-i");
  6. command.add(videoInputPath);
  7. command.add(videoOutputPath);
  8.  
  9. for(String c:command) {
  10. System.out.print(c);
  11. }
  12.  
  13. ProcessBuilder builder = new ProcessBuilder(command);
  14. Process process = builder.start();
  15.  
  16. InputStream errorStream = process.getErrorStream();
  17. InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
  18. BufferedReader br = new BufferedReader(inputStreamReader);
  19.  
  20. String line = "";
  21. //一直读取到最后一行
  22. while((line=br.readLine()) !=null ) {
  23. }
  24.  
  25. if(br!=null) {
  26. br.close();
  27. }
  28.  
  29. if(inputStreamReader!=null) {
  30. inputStreamReader.close();
  31. }
  32.  
  33. if(errorStream!=null) {
  34. errorStream.close();
  35. }
  36.  
  37. }

  1. package com.imooc.utils;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. public class FFMpegTest {
  10.  
  11. private String ffmpegEXE;
  12.  
  13. public FFMpegTest(String ffmpegEXE) {
  14. super();
  15. this.ffmpegEXE = ffmpegEXE;
  16. }
  17.  
  18. public void convertor(String videoInputPath,String videoOutputPath) throws Exception{
  19. //$ ffmpeg -i input.mp4 output.avi
  20. List<String> command = new ArrayList<>();
  21. command.add(ffmpegEXE);
  22. command.add("-i");
  23. command.add(videoInputPath);
  24. command.add(videoOutputPath);
  25.  
  26. for(String c:command) {
  27. System.out.print(c);
  28. }
  29.  
  30. ProcessBuilder builder = new ProcessBuilder(command);
  31. Process process = builder.start();
  32.  
  33. InputStream errorStream = process.getErrorStream();
  34. InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
  35. BufferedReader br = new BufferedReader(inputStreamReader);
  36.  
  37. String line = "";
  38. //一直读取到最后一行
  39. while((line=br.readLine()) !=null ) {
  40. }
  41.  
  42. if(br!=null) {
  43. br.close();
  44. }
  45.  
  46. if(inputStreamReader!=null) {
  47. inputStreamReader.close();
  48. }
  49.  
  50. if(errorStream!=null) {
  51. errorStream.close();
  52. }
  53.  
  54. }
  55.  
  56. public static void main(String[] args) {
  57. FFMpegTest ffmpeg = new FFMpegTest("F:\\Garyffmpeg\\ffmpeg\\bin\\ffmpeg.exe");
  58. try {
  59. ffmpeg.convertor("E:\\19222\\毕业生.mp4","E:\\19222\\毕2.avi");
  60. } catch (Exception e) {
  61. // TODO Auto-generated catch block
  62. e.printStackTrace();
  63. }
  64. }
  65.  
  66. }

FFMpegTest.java

  1. package com.imooc.controller;
  2.  
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.InputStream;
  6. import java.util.UUID;
  7.  
  8. import org.apache.commons.lang3.StringUtils;
  9. import org.apache.tomcat.util.http.fileupload.IOUtils;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.web.bind.annotation.PostMapping;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RequestParam;
  14. import org.springframework.web.bind.annotation.RestController;
  15. import org.springframework.web.multipart.MultipartFile;
  16.  
  17. import com.imooc.pojo.Bgm;
  18. import com.imooc.pojo.Users;
  19. import com.imooc.service.BgmService;
  20. import com.imooc.utils.IMoocJSONResult;
  21. import com.imooc.utils.MergeVideoMp3;
  22.  
  23. import io.swagger.annotations.Api;
  24. import io.swagger.annotations.ApiImplicitParam;
  25. import io.swagger.annotations.ApiImplicitParams;
  26. import io.swagger.annotations.ApiOperation;
  27. import io.swagger.annotations.ApiParam;
  28.  
  29. @RestController
  30. @Api(value="视频相关业务的接口",tags= {"视频相关业务的controller"})
  31. @RequestMapping("/video")
  32. public class VideoController extends BasicController{
  33.  
  34. @Autowired
  35. private BgmService bgmService;
  36.  
  37. @ApiOperation(value="用户视频", notes="上传视频的接口")
  38. @ApiImplicitParams({
  39. @ApiImplicitParam(name="userId",value="用户id",required=true,
  40. dataType="String" ,paramType="form"),
  41. @ApiImplicitParam(name="bgmId",value="背景音乐id",required=false,
  42. dataType="String" ,paramType="form"),
  43. @ApiImplicitParam(name="videoSeconds",value="背景音乐播放长度",required=true,
  44. dataType="String" ,paramType="form"),
  45. @ApiImplicitParam(name="videoWidth",value="视频的宽度",required=true,
  46. dataType="String" ,paramType="form"),
  47. @ApiImplicitParam(name="videoHeight",value="视频的高度",required=true,
  48. dataType="String" ,paramType="form"),
  49. @ApiImplicitParam(name="desc",value="视频的描述",required=false,
  50. dataType="String" ,paramType="form")
  51. })
  52.  
  53. @PostMapping(value="/upload",headers="content-type=multipart/form-data")
  54. public IMoocJSONResult uploadFace(String userId,
  55. String bgmId,double videoSeconds,int videoWidth,int videoHeight,String desc,
  56. @ApiParam(value="短视频",required=true)
  57. MultipartFile file) throws Exception {
  58.  
  59. if(StringUtils.isBlank(userId)) {
  60. return IMoocJSONResult.errorMsg("用户id不能为空...");
  61. }
  62.  
  63. //文件保存命名空间
  64. //String fileSpace = "F:/imooc-video-gary";
  65. //保存到数据库中的相对路径
  66. String uploadPathDB = "/" + userId + "/video";
  67.  
  68. FileOutputStream fileOutputStream = null;
  69. InputStream inputStream = null;
  70. String finalVideoPath = "";
  71. try {
  72. if( file != null ) {
  73.  
  74. String fileName = file.getOriginalFilename();
  75. if(StringUtils.isNoneBlank(fileName)) {
  76. //文件上传的最终保存路径
  77.  
  78. finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
  79. //设置数据库保存的路径
  80. uploadPathDB += ("/" + fileName);
  81.  
  82. File outFile = new File(finalVideoPath);
  83. if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
  84. //创建父文件夹
  85. outFile.getParentFile().mkdirs();
  86. }
  87.  
  88. fileOutputStream = new FileOutputStream(outFile);
  89. inputStream = file.getInputStream();
  90. IOUtils.copy(inputStream, fileOutputStream);
  91. }
  92.  
  93. }else {
  94. return IMoocJSONResult.errorMsg("上传出错...");
  95. }
  96. } catch (Exception e) {
  97. // TODO Auto-generated catch block
  98. e.printStackTrace();
  99. return IMoocJSONResult.errorMsg("上传出错...");
  100. }finally {
  101. if(fileOutputStream != null) {
  102. fileOutputStream.flush();
  103. fileOutputStream.close();
  104. }
  105. }
  106.  
  107. //判断bgmId是否为空,
  108. //如果不为空,那就查询bgm的信息,并且合并视频生成新的视频
  109.  
  110. if(StringUtils.isNotBlank(bgmId)) {
  111. Bgm bgm = bgmService.queryBgmById(bgmId);
  112. String mp3InputPath = FILE_SPACE + bgm.getPath();
  113. //System.out.println("1:mp3InputPath + "+mp3InputPath);
  114. MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE);
  115. String videoInputPath = finalVideoPath;
  116.  
  117. String videdoOutputName = UUID.randomUUID().toString() + ".mp4";
  118. uploadPathDB = "/" + userId + "/video" + "/" +videdoOutputName;
  119. finalVideoPath = FILE_SPACE + uploadPathDB;
  120. tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
  121.  
  122. }
  123.  
  124. System.out.println("uploadPathDB="+uploadPathDB);
  125. System.out.println("finalVideoPath="+finalVideoPath);
  126.  
  127. return IMoocJSONResult.ok();
  128. }
  129.  
  130. }

VideoController.java

  1. const app = getApp()
  2.  
  3. Page({
  4. data: {
  5. bgmList:[],
  6. serverUrl:"",
  7. videoParams:{}
  8. },
  9.  
  10. onLoad: function (params) {
  11. var me = this;
  12. console.log(params);
  13. me.setData({
  14. videoParams: params
  15. });
  16.  
  17. wx.showLoading({
  18. title: '请等待...',
  19. });
  20. // 调用后端
  21. var serverUrl = app.serverUrl;
  22. wx.request({
  23. url: serverUrl + '/bgm/list',
  24. method: "POST",
  25. header: {
  26. 'content-type': 'application/json' // 默认值
  27. },
  28. success: function (res) {
  29. console.log(res.data);
  30. wx.hideLoading();
  31. if (res.data.status == 200) {
  32. var bgmList = res.data.data;
  33. me.setData({
  34. bgmList:bgmList,
  35. serverUrl: serverUrl
  36. });
  37. }
  38. }
  39. })
  40.  
  41. },
  42.  
  43. upload: function (e) {
  44. var me = this;
  45.  
  46. var bgmId = e.detail.value.bgmId;
  47. var desc = e.detail.value.desc;
  48.  
  49. console.log("bgmId:" + bgmId);
  50. console.log("desc:" + desc);
  51.  
  52. var duration = me.data.videoParams.duration;
  53. var tmpheight = me.data.videoParams.tmpheight;
  54. var tmpwidth = me.data.videoParams.tmpwidth;
  55. var tmpVideoUrl = me.data.videoParams.tmpVideoUrl;
  56. var tmpCoverUrl = me.data.videoParams.tmpCoverUrl;
  57.  
  58. //上传短视频
  59. wx.showLoading({
  60. title: '上传中...',
  61. })
  62.  
  63. var serverUrl = app.serverUrl;
  64. wx.uploadFile({
  65. url: serverUrl + '/video/upload',
  66. formData: {
  67. userId: app.userInfo.id,
  68. bgmId: bgmId,
  69. desc: desc,
  70. videoSeconds: duration,
  71. videoWidth: tmpheight,
  72. videoHeight: tmpwidth,
  73. },
  74. filePath: tmpVideoUrl,
  75. name: 'file',
  76. header: {
  77. 'content-type': 'application/json' // 默认值
  78. },
  79. success: function (res) {
  80. var data = JSON.parse(res.data);
  81. console.log(res);
  82. wx.hideLoading();
  83. if (data.status == 200) {
  84. wx.showToast({
  85. title: '上传成功',
  86. icon: "success"
  87. });
  88. }
  89. }
  90. })
  91.  
  92. }
  93.  
  94. })

chooseBGM.js

保存视频到数据库中

  在VideoController中将数视频信息存储到数据库中

  1. //保存视频信息到数据库
  2. Videos video = new Videos();
  3. video.setAudioId(bgmId);
  4. video.setUserId(userId);
  5. video.setVideoSeconds((float)videoSeconds);
  6. video.setVideoHeight(videoHeight);
  7. video.setVideoWidth(videoWidth);
  8. video.setVideoDesc(desc);
  9. video.setVideoPath(uploadPathDB);
  10. video.setStatus(VideoStatusEnum.SUCCESS.value);
  11. video.setCreateTime(new Date());
  12.  
  13. videoService.saveVideo(video);

  保存数据库方法

  1. @Transactional(propagation = Propagation.REQUIRED)
  2. @Override
  3. public void saveVideo(Videos video) {
  4.  
  5. String id = sid.nextShort();
  6. video.setId(id);
  7.  
  8. videosMapper.insertSelective(video);
  9. }

  1. package com.imooc.service;
  2.  
  3. import java.util.List;
  4.  
  5. import com.imooc.pojo.Bgm;
  6. import com.imooc.pojo.Users;
  7. import com.imooc.pojo.Videos;
  8.  
  9. public interface VideoService {
  10.  
  11. //保存视频
  12. public void saveVideo(Videos video);
  13.  
  14. }

VideoService.java

  1. package com.imooc.server.impl;
  2.  
  3. import java.util.List;
  4.  
  5. import org.n3r.idworker.Sid;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.transaction.annotation.Propagation;
  9. import org.springframework.transaction.annotation.Transactional;
  10.  
  11. import com.imooc.mapper.BgmMapper;
  12. import com.imooc.mapper.UsersMapper;
  13. import com.imooc.mapper.VideosMapper;
  14. import com.imooc.pojo.Bgm;
  15. import com.imooc.pojo.Users;
  16. import com.imooc.pojo.Videos;
  17. import com.imooc.service.BgmService;
  18. import com.imooc.service.UserService;
  19. import com.imooc.service.VideoService;
  20.  
  21. import tk.mybatis.mapper.entity.Example;
  22. import tk.mybatis.mapper.entity.Example.Criteria;
  23.  
  24. @Service
  25. public class VideoServiceImpl implements VideoService {
  26.  
  27. @Autowired
  28. private VideosMapper videosMapper;
  29.  
  30. @Autowired
  31. private Sid sid;
  32.  
  33. @Transactional(propagation = Propagation.REQUIRED)
  34. @Override
  35. public void saveVideo(Videos video) {
  36.  
  37. String id = sid.nextShort();
  38. video.setId(id);
  39.  
  40. videosMapper.insertSelective(video);
  41. }
  42.  
  43. }

VideoServiceImpl.java

  1. package com.imooc.controller;
  2.  
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.InputStream;
  6. import java.util.Date;
  7. import java.util.UUID;
  8.  
  9. import org.apache.commons.lang3.StringUtils;
  10. import org.apache.tomcat.util.http.fileupload.IOUtils;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.web.bind.annotation.PostMapping;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RequestParam;
  15. import org.springframework.web.bind.annotation.RestController;
  16. import org.springframework.web.multipart.MultipartFile;
  17.  
  18. import com.imooc.enums.VideoStatusEnum;
  19. import com.imooc.pojo.Bgm;
  20. import com.imooc.pojo.Users;
  21. import com.imooc.pojo.Videos;
  22. import com.imooc.service.BgmService;
  23. import com.imooc.service.VideoService;
  24. import com.imooc.utils.IMoocJSONResult;
  25. import com.imooc.utils.MergeVideoMp3;
  26.  
  27. import io.swagger.annotations.Api;
  28. import io.swagger.annotations.ApiImplicitParam;
  29. import io.swagger.annotations.ApiImplicitParams;
  30. import io.swagger.annotations.ApiOperation;
  31. import io.swagger.annotations.ApiParam;
  32.  
  33. @RestController
  34. @Api(value="视频相关业务的接口",tags= {"视频相关业务的controller"})
  35. @RequestMapping("/video")
  36. public class VideoController extends BasicController{
  37.  
  38. @Autowired
  39. private BgmService bgmService;
  40.  
  41. @Autowired
  42. private VideoService videoService;
  43.  
  44. @ApiOperation(value="用户视频", notes="上传视频的接口")
  45. @ApiImplicitParams({
  46. @ApiImplicitParam(name="userId",value="用户id",required=true,
  47. dataType="String" ,paramType="form"),
  48. @ApiImplicitParam(name="bgmId",value="背景音乐id",required=false,
  49. dataType="String" ,paramType="form"),
  50. @ApiImplicitParam(name="videoSeconds",value="背景音乐播放长度",required=true,
  51. dataType="String" ,paramType="form"),
  52. @ApiImplicitParam(name="videoWidth",value="视频的宽度",required=true,
  53. dataType="String" ,paramType="form"),
  54. @ApiImplicitParam(name="videoHeight",value="视频的高度",required=true,
  55. dataType="String" ,paramType="form"),
  56. @ApiImplicitParam(name="desc",value="视频的描述",required=false,
  57. dataType="String" ,paramType="form")
  58. })
  59.  
  60. @PostMapping(value="/upload",headers="content-type=multipart/form-data")
  61. public IMoocJSONResult uploadFace(String userId,
  62. String bgmId,double videoSeconds,int videoWidth,int videoHeight,String desc,
  63. @ApiParam(value="短视频",required=true)
  64. MultipartFile file) throws Exception {
  65.  
  66. if(StringUtils.isBlank(userId)) {
  67. return IMoocJSONResult.errorMsg("用户id不能为空...");
  68. }
  69.  
  70. //文件保存命名空间
  71. //String fileSpace = "F:/imooc-video-gary";
  72. //保存到数据库中的相对路径
  73. String uploadPathDB = "/" + userId + "/video";
  74.  
  75. FileOutputStream fileOutputStream = null;
  76. InputStream inputStream = null;
  77. String finalVideoPath = "";
  78. try {
  79. if( file != null ) {
  80.  
  81. String fileName = file.getOriginalFilename();
  82. if(StringUtils.isNoneBlank(fileName)) {
  83. //文件上传的最终保存路径
  84.  
  85. finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
  86. //设置数据库保存的路径
  87. uploadPathDB += ("/" + fileName);
  88.  
  89. File outFile = new File(finalVideoPath);
  90. if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
  91. //创建父文件夹
  92. outFile.getParentFile().mkdirs();
  93. }
  94.  
  95. fileOutputStream = new FileOutputStream(outFile);
  96. inputStream = file.getInputStream();
  97. IOUtils.copy(inputStream, fileOutputStream);
  98. }
  99.  
  100. }else {
  101. return IMoocJSONResult.errorMsg("上传出错...");
  102. }
  103. } catch (Exception e) {
  104. // TODO Auto-generated catch block
  105. e.printStackTrace();
  106. return IMoocJSONResult.errorMsg("上传出错...");
  107. }finally {
  108. if(fileOutputStream != null) {
  109. fileOutputStream.flush();
  110. fileOutputStream.close();
  111. }
  112. }
  113.  
  114. //判断bgmId是否为空,
  115. //如果不为空,那就查询bgm的信息,并且合并视频生成新的视频
  116.  
  117. if(StringUtils.isNotBlank(bgmId)) {
  118. Bgm bgm = bgmService.queryBgmById(bgmId);
  119. String mp3InputPath = FILE_SPACE + bgm.getPath();
  120. //System.out.println("1:mp3InputPath + "+mp3InputPath);
  121. MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE);
  122. String videoInputPath = finalVideoPath;
  123.  
  124. String videdoOutputName = UUID.randomUUID().toString() + ".mp4";
  125. uploadPathDB = "/" + userId + "/video" + "/" +videdoOutputName;
  126. finalVideoPath = FILE_SPACE + uploadPathDB;
  127. tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
  128.  
  129. }
  130.  
  131. //保存视频信息到数据库
  132. Videos video = new Videos();
  133. video.setAudioId(bgmId);
  134. video.setUserId(userId);
  135. video.setVideoSeconds((float)videoSeconds);
  136. video.setVideoHeight(videoHeight);
  137. video.setVideoWidth(videoWidth);
  138. video.setVideoDesc(desc);
  139. video.setVideoPath(uploadPathDB);
  140. video.setStatus(VideoStatusEnum.SUCCESS.value);
  141. video.setCreateTime(new Date());
  142.  
  143. videoService.saveVideo(video);
  144.  
  145. return IMoocJSONResult.ok();
  146. }
  147.  
  148. }

VideoController.java

上传封面图保存到数据库中

  因为wx.uploadFile()方法上传是单文件,所以视频和封面必须要分开上传

  保存视频uploadCover(Sring userId,String videoId)方法

  1. @ApiOperation(value="上传封面", notes="上传封面的接口")
  2. @ApiImplicitParams({
  3. @ApiImplicitParam(name="userId",value="用户id",required=true,
  4. dataType="String" ,paramType="form"),
  5. @ApiImplicitParam(name="videoId",value="视频主键id",required=true,
  6. dataType="String" ,paramType="form")
  7. })
  8. @PostMapping(value="/uploadCover",headers="content-type=multipart/form-data")
  9. public IMoocJSONResult uploadCover(String userId,String videoId,
  10. @ApiParam(value="视频封面",required=true)
  11. MultipartFile file) throws Exception {
  12.  
  13. if(StringUtils.isBlank(userId) ||StringUtils.isBlank(videoId) ) {
  14. return IMoocJSONResult.errorMsg("视频主键id和用户id不能为空...");
  15. }
  16.  
  17. //文件保存命名空间
  18. //String fileSpace = "F:/imooc-video-gary";
  19. //保存到数据库中的相对路径
  20. String uploadPathDB = "/" + userId + "/video";
  21.  
  22. FileOutputStream fileOutputStream = null;
  23. InputStream inputStream = null;
  24. String finalCoverPath = "";
  25. try {
  26. if( file != null ) {
  27.  
  28. String fileName = file.getOriginalFilename();
  29. if(StringUtils.isNoneBlank(fileName)) {
  30. //文件上传的最终保存路径
  31.  
  32. finalCoverPath = FILE_SPACE + uploadPathDB + "/" + fileName;
  33. //设置数据库保存的路径
  34. uploadPathDB += ("/" + fileName);
  35.  
  36. File outFile = new File(finalCoverPath);
  37. if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
  38. //创建父文件夹
  39. outFile.getParentFile().mkdirs();
  40. }
  41.  
  42. fileOutputStream = new FileOutputStream(outFile);
  43. inputStream = file.getInputStream();
  44. IOUtils.copy(inputStream, fileOutputStream);
  45. }
  46.  
  47. }else {
  48. return IMoocJSONResult.errorMsg("上传出错...");
  49. }
  50. } catch (Exception e) {
  51. // TODO Auto-generated catch block
  52. e.printStackTrace();
  53. return IMoocJSONResult.errorMsg("上传出错...");
  54. }finally {
  55. if(fileOutputStream != null) {
  56. fileOutputStream.flush();
  57. fileOutputStream.close();
  58. }
  59. }
  60.  
  61. videoService.updateVideo(videoId, uploadPathDB);
  62.  
  63. return IMoocJSONResult.ok();
  64. }

  将视频封面保存进数据库方法

  1. @Transactional(propagation = Propagation.REQUIRED)
  2. @Override
  3. public void updateVideo(String videoId, String coverPath) {
  4.  
  5. Videos video = new Videos();
  6. video.setId(videoId);
  7. video.setCoverPath(coverPath);
  8. videosMapper.updateByPrimaryKeySelective(video);
  9.  
  10. }

  1. package com.imooc.server.impl;
  2.  
  3. import java.util.List;
  4.  
  5. import org.n3r.idworker.Sid;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.transaction.annotation.Propagation;
  9. import org.springframework.transaction.annotation.Transactional;
  10.  
  11. import com.imooc.mapper.BgmMapper;
  12. import com.imooc.mapper.UsersMapper;
  13. import com.imooc.mapper.VideosMapper;
  14. import com.imooc.pojo.Bgm;
  15. import com.imooc.pojo.Users;
  16. import com.imooc.pojo.Videos;
  17. import com.imooc.service.BgmService;
  18. import com.imooc.service.UserService;
  19. import com.imooc.service.VideoService;
  20.  
  21. import tk.mybatis.mapper.entity.Example;
  22. import tk.mybatis.mapper.entity.Example.Criteria;
  23.  
  24. @Service
  25. public class VideoServiceImpl implements VideoService {
  26.  
  27. @Autowired
  28. private VideosMapper videosMapper;
  29.  
  30. @Autowired
  31. private Sid sid;
  32.  
  33. @Transactional(propagation = Propagation.REQUIRED)
  34. @Override
  35. public String saveVideo(Videos video) {
  36.  
  37. String id = sid.nextShort();
  38. video.setId(id);
  39.  
  40. videosMapper.insertSelective(video);
  41.  
  42. return id;
  43. }
  44.  
  45. @Transactional(propagation = Propagation.REQUIRED)
  46. @Override
  47. public void updateVideo(String videoId, String coverPath) {
  48.  
  49. Videos video = new Videos();
  50. video.setId(videoId);
  51. video.setCoverPath(coverPath);
  52. videosMapper.updateByPrimaryKeySelective(video);
  53.  
  54. }
  55.  
  56. }

VideoServiceImpl.java

  1. package com.imooc.controller;
  2.  
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.InputStream;
  6. import java.util.Date;
  7. import java.util.UUID;
  8.  
  9. import org.apache.commons.lang3.StringUtils;
  10. import org.apache.tomcat.util.http.fileupload.IOUtils;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.web.bind.annotation.PostMapping;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RequestParam;
  15. import org.springframework.web.bind.annotation.RestController;
  16. import org.springframework.web.multipart.MultipartFile;
  17.  
  18. import com.imooc.enums.VideoStatusEnum;
  19. import com.imooc.pojo.Bgm;
  20. import com.imooc.pojo.Users;
  21. import com.imooc.pojo.Videos;
  22. import com.imooc.service.BgmService;
  23. import com.imooc.service.VideoService;
  24. import com.imooc.utils.IMoocJSONResult;
  25. import com.imooc.utils.MergeVideoMp3;
  26.  
  27. import io.swagger.annotations.Api;
  28. import io.swagger.annotations.ApiImplicitParam;
  29. import io.swagger.annotations.ApiImplicitParams;
  30. import io.swagger.annotations.ApiOperation;
  31. import io.swagger.annotations.ApiParam;
  32.  
  33. @RestController
  34. @Api(value="视频相关业务的接口",tags= {"视频相关业务的controller"})
  35. @RequestMapping("/video")
  36. public class VideoController extends BasicController{
  37.  
  38. @Autowired
  39. private BgmService bgmService;
  40.  
  41. @Autowired
  42. private VideoService videoService;
  43.  
  44. @ApiOperation(value="上传视频", notes="上传视频的接口")
  45. @ApiImplicitParams({
  46. @ApiImplicitParam(name="userId",value="用户id",required=true,
  47. dataType="String" ,paramType="form"),
  48. @ApiImplicitParam(name="bgmId",value="背景音乐id",required=false,
  49. dataType="String" ,paramType="form"),
  50. @ApiImplicitParam(name="videoSeconds",value="背景音乐播放长度",required=true,
  51. dataType="String" ,paramType="form"),
  52. @ApiImplicitParam(name="videoWidth",value="视频的宽度",required=true,
  53. dataType="String" ,paramType="form"),
  54. @ApiImplicitParam(name="videoHeight",value="视频的高度",required=true,
  55. dataType="String" ,paramType="form"),
  56. @ApiImplicitParam(name="desc",value="视频的描述",required=false,
  57. dataType="String" ,paramType="form")
  58. })
  59. @PostMapping(value="/upload",headers="content-type=multipart/form-data")
  60. public IMoocJSONResult uploadFace(String userId,
  61. String bgmId,double videoSeconds,int videoWidth,int videoHeight,String desc,
  62. @ApiParam(value="短视频",required=true)
  63. MultipartFile file) throws Exception {
  64.  
  65. if(StringUtils.isBlank(userId)) {
  66. return IMoocJSONResult.errorMsg("用户id不能为空...");
  67. }
  68.  
  69. //文件保存命名空间
  70. //String fileSpace = "F:/imooc-video-gary";
  71. //保存到数据库中的相对路径
  72. String uploadPathDB = "/" + userId + "/video";
  73.  
  74. FileOutputStream fileOutputStream = null;
  75. InputStream inputStream = null;
  76. String finalVideoPath = "";
  77. try {
  78. if( file != null ) {
  79.  
  80. String fileName = file.getOriginalFilename();
  81. if(StringUtils.isNoneBlank(fileName)) {
  82. //文件上传的最终保存路径
  83.  
  84. finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
  85. //设置数据库保存的路径
  86. uploadPathDB += ("/" + fileName);
  87.  
  88. File outFile = new File(finalVideoPath);
  89. if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
  90. //创建父文件夹
  91. outFile.getParentFile().mkdirs();
  92. }
  93.  
  94. fileOutputStream = new FileOutputStream(outFile);
  95. inputStream = file.getInputStream();
  96. IOUtils.copy(inputStream, fileOutputStream);
  97. }
  98.  
  99. }else {
  100. return IMoocJSONResult.errorMsg("上传出错...");
  101. }
  102. } catch (Exception e) {
  103. // TODO Auto-generated catch block
  104. e.printStackTrace();
  105. return IMoocJSONResult.errorMsg("上传出错...");
  106. }finally {
  107. if(fileOutputStream != null) {
  108. fileOutputStream.flush();
  109. fileOutputStream.close();
  110. }
  111. }
  112.  
  113. //判断bgmId是否为空,
  114. //如果不为空,那就查询bgm的信息,并且合并视频生成新的视频
  115.  
  116. if(StringUtils.isNotBlank(bgmId)) {
  117. Bgm bgm = bgmService.queryBgmById(bgmId);
  118. String mp3InputPath = FILE_SPACE + bgm.getPath();
  119. //System.out.println("1:mp3InputPath + "+mp3InputPath);
  120. MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE);
  121. String videoInputPath = finalVideoPath;
  122.  
  123. String videdoOutputName = UUID.randomUUID().toString() + ".mp4";
  124. uploadPathDB = "/" + userId + "/video" + "/" +videdoOutputName;
  125. finalVideoPath = FILE_SPACE + uploadPathDB;
  126. tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
  127.  
  128. }
  129.  
  130. //保存视频信息到数据库
  131. Videos video = new Videos();
  132. video.setAudioId(bgmId);
  133. video.setUserId(userId);
  134. video.setVideoSeconds((float)videoSeconds);
  135. video.setVideoHeight(videoHeight);
  136. video.setVideoWidth(videoWidth);
  137. video.setVideoDesc(desc);
  138. video.setVideoPath(uploadPathDB);
  139. video.setStatus(VideoStatusEnum.SUCCESS.value);
  140. video.setCreateTime(new Date());
  141.  
  142. String videoId = videoService.saveVideo(video);
  143.  
  144. return IMoocJSONResult.ok(videoId);
  145. }
  146.  
  147. @ApiOperation(value="上传封面", notes="上传封面的接口")
  148. @ApiImplicitParams({
  149. @ApiImplicitParam(name="userId",value="用户id",required=true,
  150. dataType="String" ,paramType="form"),
  151. @ApiImplicitParam(name="videoId",value="视频主键id",required=true,
  152. dataType="String" ,paramType="form")
  153. })
  154. @PostMapping(value="/uploadCover",headers="content-type=multipart/form-data")
  155. public IMoocJSONResult uploadCover(String userId,String videoId,
  156. @ApiParam(value="视频封面",required=true)
  157. MultipartFile file) throws Exception {
  158.  
  159. if(StringUtils.isBlank(userId) ||StringUtils.isBlank(videoId) ) {
  160. return IMoocJSONResult.errorMsg("视频主键id和用户id不能为空...");
  161. }
  162.  
  163. //文件保存命名空间
  164. //String fileSpace = "F:/imooc-video-gary";
  165. //保存到数据库中的相对路径
  166. String uploadPathDB = "/" + userId + "/video";
  167.  
  168. FileOutputStream fileOutputStream = null;
  169. InputStream inputStream = null;
  170. String finalCoverPath = "";
  171. try {
  172. if( file != null ) {
  173.  
  174. String fileName = file.getOriginalFilename();
  175. if(StringUtils.isNoneBlank(fileName)) {
  176. //文件上传的最终保存路径
  177.  
  178. finalCoverPath = FILE_SPACE + uploadPathDB + "/" + fileName;
  179. //设置数据库保存的路径
  180. uploadPathDB += ("/" + fileName);
  181.  
  182. File outFile = new File(finalCoverPath);
  183. if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
  184. //创建父文件夹
  185. outFile.getParentFile().mkdirs();
  186. }
  187.  
  188. fileOutputStream = new FileOutputStream(outFile);
  189. inputStream = file.getInputStream();
  190. IOUtils.copy(inputStream, fileOutputStream);
  191. }
  192.  
  193. }else {
  194. return IMoocJSONResult.errorMsg("上传出错...");
  195. }
  196. } catch (Exception e) {
  197. // TODO Auto-generated catch block
  198. e.printStackTrace();
  199. return IMoocJSONResult.errorMsg("上传出错...");
  200. }finally {
  201. if(fileOutputStream != null) {
  202. fileOutputStream.flush();
  203. fileOutputStream.close();
  204. }
  205. }
  206.  
  207. videoService.updateVideo(videoId, uploadPathDB);
  208.  
  209. return IMoocJSONResult.ok();
  210. }
  211.  
  212. }

VideoController.java

小程序端上传视频业务流程实现

  当小程序端成功上传视频回调函数返回200时,上传视频封面

  1. if (data.status == 200) {
  2.  
  3. var videoId = data.data;
  4.  
  5. //上传短视频封面
  6. wx.showLoading({
  7. title: '上传中...',
  8. })
  9. wx.uploadFile({
  10. url: serverUrl + '/video/uploadCover',
  11. formData: {
  12. userId: app.userInfo.id,
  13. videoId: videoId
  14. },
  15. filePath: tmpCoverUrl,
  16. name: 'file',
  17. header: {
  18. 'content-type': 'application/json' // 默认值
  19. },
  20. success: function (res) {
  21. var data = JSON.parse(res.data);
  22. wx.hideLoading();
  23. if (data.status == 200) {
  24. wx.showToast({
  25. title: '上传成功',
  26. icon: "success"
  27. });
  28. wx.navigateBack({
  29. delta:1,
  30. })
  31. } else {
  32. wx.showToast({
  33. title: '上传失败!',
  34. icon: "success"
  35. });
  36. }
  37. }
  38. })
  39.  
  40. }else{
  41. wx.showToast({
  42. title: '上传失败!',
  43. icon:"success"
  44. });
  45. }
  1. const app = getApp()
  2.  
  3. Page({
  4. data: {
  5. bgmList:[],
  6. serverUrl:"",
  7. videoParams:{}
  8. },
  9.  
  10. onLoad: function (params) {
  11. var me = this;
  12. console.log(params);
  13. me.setData({
  14. videoParams: params
  15. });
  16.  
  17. wx.showLoading({
  18. title: '请等待...',
  19. });
  20. // 调用后端
  21. var serverUrl = app.serverUrl;
  22. wx.request({
  23. url: serverUrl + '/bgm/list',
  24. method: "POST",
  25. header: {
  26. 'content-type': 'application/json' // 默认值
  27. },
  28. success: function (res) {
  29. console.log(res.data);
  30. wx.hideLoading();
  31. if (res.data.status == 200) {
  32. var bgmList = res.data.data;
  33. me.setData({
  34. bgmList:bgmList,
  35. serverUrl: serverUrl
  36. });
  37. }
  38. }
  39. })
  40.  
  41. },
  42.  
  43. upload: function (e) {
  44. var me = this;
  45.  
  46. var bgmId = e.detail.value.bgmId;
  47. var desc = e.detail.value.desc;
  48.  
  49. console.log("bgmId:" + bgmId);
  50. console.log("desc:" + desc);
  51.  
  52. var duration = me.data.videoParams.duration;
  53. var tmpheight = me.data.videoParams.tmpheight;
  54. var tmpwidth = me.data.videoParams.tmpwidth;
  55. var tmpVideoUrl = me.data.videoParams.tmpVideoUrl;
  56. var tmpCoverUrl = me.data.videoParams.tmpCoverUrl;
  57.  
  58. //上传短视频
  59. wx.showLoading({
  60. title: '上传中...',
  61. })
  62.  
  63. var serverUrl = app.serverUrl;
  64. wx.uploadFile({
  65. url: serverUrl + '/video/upload',
  66. formData: {
  67. userId: app.userInfo.id,
  68. bgmId: bgmId,
  69. desc: desc,
  70. videoSeconds: duration,
  71. videoWidth: tmpheight,
  72. videoHeight: tmpwidth,
  73. },
  74. filePath: tmpVideoUrl,
  75. name: 'file',
  76. header: {
  77. 'content-type': 'application/json' // 默认值
  78. },
  79. success: function (res) {
  80. var data = JSON.parse(res.data);
  81. wx.hideLoading();
  82. if (data.status == 200) {
  83.  
  84. var videoId = data.data;
  85.  
  86. //上传短视频封面
  87. wx.showLoading({
  88. title: '上传中...',
  89. })
  90. wx.uploadFile({
  91. url: serverUrl + '/video/uploadCover',
  92. formData: {
  93. userId: app.userInfo.id,
  94. videoId: videoId
  95. },
  96. filePath: tmpCoverUrl,
  97. name: 'file',
  98. header: {
  99. 'content-type': 'application/json' // 默认值
  100. },
  101. success: function (res) {
  102. var data = JSON.parse(res.data);
  103. wx.hideLoading();
  104. if (data.status == 200) {
  105. wx.showToast({
  106. title: '上传成功',
  107. icon: "success"
  108. });
  109. wx.navigateBack({
  110. delta:1,
  111. })
  112. } else {
  113. wx.showToast({
  114. title: '上传失败!',
  115. icon: "success"
  116. });
  117. }
  118. }
  119. })
  120.  
  121. }else{
  122. wx.showToast({
  123. title: '上传失败!',
  124. icon:"success"
  125. });
  126. }
  127. }
  128. })
  129.  
  130. }
  131.  
  132. })

chooseBgm.js

  为避免在微信小程序端截不到视频封面的图片,即使用ffmpeg技术去实现

  截图思路:截视频的第1s

  1. bin>ffmpeg.exe -ss 00:00:01 -y -i new.mp4 -vframes 1 new2.jpg

  1. package com.imooc.utils;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.util.List;
  8.  
  9. /**
  10. *
  11. * @Description: 获取视频的信息
  12. */
  13. public class FetchVideoCover {
  14. // 视频路径
  15. private String ffmpegEXE;
  16.  
  17. public void getCover(String videoInputPath, String coverOutputPath) throws IOException, InterruptedException {
  18. // ffmpeg.exe -ss 00:00:01 -i spring.mp4 -vframes 1 bb.jpg
  19. List<String> command = new java.util.ArrayList<String>();
  20. command.add(ffmpegEXE);
  21.  
  22. // 指定截取第1秒
  23. command.add("-ss");
  24. command.add("00:00:01");
  25.  
  26. command.add("-y");
  27. command.add("-i");
  28. command.add(videoInputPath);
  29.  
  30. command.add("-vframes");
  31. command.add("1");
  32.  
  33. command.add(coverOutputPath);
  34.  
  35. for (String c : command) {
  36. System.out.print(c + " ");
  37. }
  38.  
  39. ProcessBuilder builder = new ProcessBuilder(command);
  40. Process process = builder.start();
  41.  
  42. InputStream errorStream = process.getErrorStream();
  43. InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
  44. BufferedReader br = new BufferedReader(inputStreamReader);
  45.  
  46. String line = "";
  47. while ( (line = br.readLine()) != null ) {
  48. }
  49.  
  50. if (br != null) {
  51. br.close();
  52. }
  53. if (inputStreamReader != null) {
  54. inputStreamReader.close();
  55. }
  56. if (errorStream != null) {
  57. errorStream.close();
  58. }
  59. }
  60.  
  61. public String getFfmpegEXE() {
  62. return ffmpegEXE;
  63. }
  64.  
  65. public void setFfmpegEXE(String ffmpegEXE) {
  66. this.ffmpegEXE = ffmpegEXE;
  67. }
  68.  
  69. public FetchVideoCover() {
  70. super();
  71. }
  72.  
  73. public FetchVideoCover(String ffmpegEXE) {
  74. this.ffmpegEXE = ffmpegEXE;
  75. }
  76.  
  77. public static void main(String[] args) {
  78. // 获取视频信息。
  79. FetchVideoCover videoInfo = new FetchVideoCover("F:\\Garyffmpeg\\ffmpeg\\bin\\ffmpeg.exe");
  80. try {
  81. videoInfo.getCover("e:\\19222\\Gary12.mp4","e:\\19222\\Gary1212.jpg");
  82.  
  83. } catch (Exception e) {
  84. e.printStackTrace();
  85. }
  86. }
  87. }

FetchVideoCover.java

上传视频流程整合视频截图功能

  在VideoController.java中实现视频截图功能并保存到数据库中

  1. //对视频封面进行截图
  2. FetchVideoCover videoInfo = new FetchVideoCover(FFMPEG_EXE);
  3. videoInfo.getCover(finalVideoPath,FILE_SPACE + coverPathDB);
  4.  
  5. //保存视频信息到数据库
  6. Videos video = new Videos();
  7. video.setAudioId(bgmId);
  8. video.setUserId(userId);
  9. video.setVideoSeconds((float)videoSeconds);
  10. video.setVideoHeight(videoHeight);
  11. video.setVideoWidth(videoWidth);
  12. video.setVideoDesc(desc);
  13. video.setVideoPath(uploadPathDB);
  14. video.setCoverPath(coverPathDB);
  15. video.setStatus(VideoStatusEnum.SUCCESS.value);
  16. video.setCreateTime(new Date());
  1. package com.imooc.utils;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.util.List;
  8.  
  9. /**
  10. *
  11. * @Description: 获取视频的信息
  12. */
  13. public class FetchVideoCover {
  14. // 视频路径
  15. private String ffmpegEXE;
  16.  
  17. public void getCover(String videoInputPath, String coverOutputPath) throws IOException, InterruptedException {
  18. // ffmpeg.exe -ss 00:00:01 -i spring.mp4 -vframes 1 bb.jpg
  19. List<String> command = new java.util.ArrayList<String>();
  20. command.add(ffmpegEXE);
  21.  
  22. // 指定截取第1秒
  23. command.add("-ss");
  24. command.add("00:00:01");
  25.  
  26. command.add("-y");
  27. command.add("-i");
  28. command.add(videoInputPath);
  29.  
  30. command.add("-vframes");
  31. command.add("1");
  32.  
  33. command.add(coverOutputPath);
  34.  
  35. for (String c : command) {
  36. System.out.print(c + " ");
  37. }
  38.  
  39. ProcessBuilder builder = new ProcessBuilder(command);
  40. Process process = builder.start();
  41.  
  42. InputStream errorStream = process.getErrorStream();
  43. InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
  44. BufferedReader br = new BufferedReader(inputStreamReader);
  45.  
  46. String line = "";
  47. while ( (line = br.readLine()) != null ) {
  48. }
  49.  
  50. if (br != null) {
  51. br.close();
  52. }
  53. if (inputStreamReader != null) {
  54. inputStreamReader.close();
  55. }
  56. if (errorStream != null) {
  57. errorStream.close();
  58. }
  59. }
  60.  
  61. public String getFfmpegEXE() {
  62. return ffmpegEXE;
  63. }
  64.  
  65. public void setFfmpegEXE(String ffmpegEXE) {
  66. this.ffmpegEXE = ffmpegEXE;
  67. }
  68.  
  69. public FetchVideoCover() {
  70. super();
  71. }
  72.  
  73. public FetchVideoCover(String ffmpegEXE) {
  74. this.ffmpegEXE = ffmpegEXE;
  75. }
  76.  
  77. public static void main(String[] args) {
  78. // 获取视频信息。
  79. FetchVideoCover videoInfo = new FetchVideoCover("F:\\Garyffmpeg\\ffmpeg\\bin\\ffmpeg.exe");
  80. try {
  81. videoInfo.getCover("e:\\19222\\Gary12.mp4","e:\\19222\\Gary1212.jpg");
  82.  
  83. } catch (Exception e) {
  84. e.printStackTrace();
  85. }
  86. }
  87. }

FetchVideoCover.java

  1. package com.imooc.controller;
  2.  
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.InputStream;
  6. import java.util.Date;
  7. import java.util.UUID;
  8.  
  9. import org.apache.commons.lang3.StringUtils;
  10. import org.apache.tomcat.util.http.fileupload.IOUtils;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.web.bind.annotation.PostMapping;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RequestParam;
  15. import org.springframework.web.bind.annotation.RestController;
  16. import org.springframework.web.multipart.MultipartFile;
  17.  
  18. import com.imooc.enums.VideoStatusEnum;
  19. import com.imooc.pojo.Bgm;
  20. import com.imooc.pojo.Users;
  21. import com.imooc.pojo.Videos;
  22. import com.imooc.service.BgmService;
  23. import com.imooc.service.VideoService;
  24. import com.imooc.utils.FetchVideoCover;
  25. import com.imooc.utils.IMoocJSONResult;
  26. import com.imooc.utils.MergeVideoMp3;
  27.  
  28. import io.swagger.annotations.Api;
  29. import io.swagger.annotations.ApiImplicitParam;
  30. import io.swagger.annotations.ApiImplicitParams;
  31. import io.swagger.annotations.ApiOperation;
  32. import io.swagger.annotations.ApiParam;
  33.  
  34. @RestController
  35. @Api(value="视频相关业务的接口",tags= {"视频相关业务的controller"})
  36. @RequestMapping("/video")
  37. public class VideoController extends BasicController{
  38.  
  39. @Autowired
  40. private BgmService bgmService;
  41.  
  42. @Autowired
  43. private VideoService videoService;
  44.  
  45. @ApiOperation(value="上传视频", notes="上传视频的接口")
  46. @ApiImplicitParams({
  47. @ApiImplicitParam(name="userId",value="用户id",required=true,
  48. dataType="String" ,paramType="form"),
  49. @ApiImplicitParam(name="bgmId",value="背景音乐id",required=false,
  50. dataType="String" ,paramType="form"),
  51. @ApiImplicitParam(name="videoSeconds",value="背景音乐播放长度",required=true,
  52. dataType="String" ,paramType="form"),
  53. @ApiImplicitParam(name="videoWidth",value="视频的宽度",required=true,
  54. dataType="String" ,paramType="form"),
  55. @ApiImplicitParam(name="videoHeight",value="视频的高度",required=true,
  56. dataType="String" ,paramType="form"),
  57. @ApiImplicitParam(name="desc",value="视频的描述",required=false,
  58. dataType="String" ,paramType="form")
  59. })
  60. @PostMapping(value="/upload",headers="content-type=multipart/form-data")
  61. public IMoocJSONResult uploadFace(String userId,
  62. String bgmId,double videoSeconds,int videoWidth,int videoHeight,String desc,
  63. @ApiParam(value="短视频",required=true)
  64. MultipartFile file) throws Exception {
  65.  
  66. if(StringUtils.isBlank(userId)) {
  67. return IMoocJSONResult.errorMsg("用户id不能为空...");
  68. }
  69.  
  70. //文件保存命名空间
  71. //String fileSpace = "F:/imooc-video-gary";
  72. //保存到数据库中的相对路径
  73. String uploadPathDB = "/" + userId + "/video";
  74. String coverPathDB = "/" + userId + "/video";
  75.  
  76. FileOutputStream fileOutputStream = null;
  77. InputStream inputStream = null;
  78. String finalVideoPath = "";
  79. try {
  80. if( file != null ) {
  81.  
  82. String fileName = file.getOriginalFilename();
  83. //Gary.mp4 使用spilt进行分割
  84. String fileNamePrefix = fileName.split("\\.")[0];
  85.  
  86. if(StringUtils.isNoneBlank(fileName)) {
  87. //文件上传的最终保存路径
  88.  
  89. finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
  90. //设置数据库保存的路径
  91. uploadPathDB += ("/" + fileName);
  92. coverPathDB = coverPathDB + "/" + fileNamePrefix + ".jpg";
  93.  
  94. File outFile = new File(finalVideoPath);
  95. if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
  96. //创建父文件夹
  97. outFile.getParentFile().mkdirs();
  98. }
  99.  
  100. fileOutputStream = new FileOutputStream(outFile);
  101. inputStream = file.getInputStream();
  102. IOUtils.copy(inputStream, fileOutputStream);
  103. }
  104.  
  105. }else {
  106. return IMoocJSONResult.errorMsg("上传出错...");
  107. }
  108. } catch (Exception e) {
  109. // TODO Auto-generated catch block
  110. e.printStackTrace();
  111. return IMoocJSONResult.errorMsg("上传出错...");
  112. }finally {
  113. if(fileOutputStream != null) {
  114. fileOutputStream.flush();
  115. fileOutputStream.close();
  116. }
  117. }
  118.  
  119. //判断bgmId是否为空,
  120. //如果不为空,那就查询bgm的信息,并且合并视频生成新的视频
  121.  
  122. if(StringUtils.isNotBlank(bgmId)) {
  123. Bgm bgm = bgmService.queryBgmById(bgmId);
  124. String mp3InputPath = FILE_SPACE + bgm.getPath();
  125. //System.out.println("1:mp3InputPath + "+mp3InputPath);
  126. MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE);
  127. String videoInputPath = finalVideoPath;
  128.  
  129. String videdoOutputName = UUID.randomUUID().toString() + ".mp4";
  130. uploadPathDB = "/" + userId + "/video" + "/" +videdoOutputName;
  131. finalVideoPath = FILE_SPACE + uploadPathDB;
  132. tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
  133.  
  134. }
  135.  
  136. //对视频封面进行截图
  137. FetchVideoCover videoInfo = new FetchVideoCover(FFMPEG_EXE);
  138. videoInfo.getCover(finalVideoPath,FILE_SPACE + coverPathDB);
  139.  
  140. //保存视频信息到数据库
  141. Videos video = new Videos();
  142. video.setAudioId(bgmId);
  143. video.setUserId(userId);
  144. video.setVideoSeconds((float)videoSeconds);
  145. video.setVideoHeight(videoHeight);
  146. video.setVideoWidth(videoWidth);
  147. video.setVideoDesc(desc);
  148. video.setVideoPath(uploadPathDB);
  149. video.setCoverPath(coverPathDB);
  150. video.setStatus(VideoStatusEnum.SUCCESS.value);
  151. video.setCreateTime(new Date());
  152.  
  153. String videoId = videoService.saveVideo(video);
  154.  
  155. return IMoocJSONResult.ok(videoId);
  156. }
  157.  
  158. @ApiOperation(value="上传封面", notes="上传封面的接口")
  159. @ApiImplicitParams({
  160. @ApiImplicitParam(name="userId",value="用户id",required=true,
  161. dataType="String" ,paramType="form"),
  162. @ApiImplicitParam(name="videoId",value="视频主键id",required=true,
  163. dataType="String" ,paramType="form")
  164. })
  165. @PostMapping(value="/uploadCover",headers="content-type=multipart/form-data")
  166. public IMoocJSONResult uploadCover(String userId,String videoId,
  167. @ApiParam(value="视频封面",required=true)
  168. MultipartFile file) throws Exception {
  169.  
  170. if(StringUtils.isBlank(userId) ||StringUtils.isBlank(videoId) ) {
  171. return IMoocJSONResult.errorMsg("视频主键id和用户id不能为空...");
  172. }
  173.  
  174. //文件保存命名空间
  175. //String fileSpace = "F:/imooc-video-gary";
  176. //保存到数据库中的相对路径
  177. String uploadPathDB = "/" + userId + "/video";
  178.  
  179. FileOutputStream fileOutputStream = null;
  180. InputStream inputStream = null;
  181. String finalCoverPath = "";
  182. try {
  183. if( file != null ) {
  184.  
  185. String fileName = file.getOriginalFilename();
  186. if(StringUtils.isNoneBlank(fileName)) {
  187. //文件上传的最终保存路径
  188.  
  189. finalCoverPath = FILE_SPACE + uploadPathDB + "/" + fileName;
  190. //设置数据库保存的路径
  191. uploadPathDB += ("/" + fileName);
  192.  
  193. File outFile = new File(finalCoverPath);
  194. if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) {
  195. //创建父文件夹
  196. outFile.getParentFile().mkdirs();
  197. }
  198.  
  199. fileOutputStream = new FileOutputStream(outFile);
  200. inputStream = file.getInputStream();
  201. IOUtils.copy(inputStream, fileOutputStream);
  202. }
  203.  
  204. }else {
  205. return IMoocJSONResult.errorMsg("上传出错...");
  206. }
  207. } catch (Exception e) {
  208. // TODO Auto-generated catch block
  209. e.printStackTrace();
  210. return IMoocJSONResult.errorMsg("上传出错...");
  211. }finally {
  212. if(fileOutputStream != null) {
  213. fileOutputStream.flush();
  214. fileOutputStream.close();
  215. }
  216. }
  217.  
  218. videoService.updateVideo(videoId, uploadPathDB);
  219.  
  220. return IMoocJSONResult.ok();
  221. }
  222.  
  223. }

VideoController.java

  1. const app = getApp()
  2.  
  3. Page({
  4. data: {
  5. bgmList:[],
  6. serverUrl:"",
  7. videoParams:{}
  8. },
  9.  
  10. onLoad: function (params) {
  11. var me = this;
  12. console.log(params);
  13. me.setData({
  14. videoParams: params
  15. });
  16.  
  17. wx.showLoading({
  18. title: '请等待...',
  19. });
  20. // 调用后端
  21. var serverUrl = app.serverUrl;
  22. wx.request({
  23. url: serverUrl + '/bgm/list',
  24. method: "POST",
  25. header: {
  26. 'content-type': 'application/json' // 默认值
  27. },
  28. success: function (res) {
  29. console.log(res.data);
  30. wx.hideLoading();
  31. if (res.data.status == 200) {
  32. var bgmList = res.data.data;
  33. me.setData({
  34. bgmList:bgmList,
  35. serverUrl: serverUrl
  36. });
  37. }
  38. }
  39. })
  40.  
  41. },
  42.  
  43. upload: function (e) {
  44. var me = this;
  45.  
  46. var bgmId = e.detail.value.bgmId;
  47. var desc = e.detail.value.desc;
  48.  
  49. console.log("bgmId:" + bgmId);
  50. console.log("desc:" + desc);
  51.  
  52. var duration = me.data.videoParams.duration;
  53. var tmpheight = me.data.videoParams.tmpheight;
  54. var tmpwidth = me.data.videoParams.tmpwidth;
  55. var tmpVideoUrl = me.data.videoParams.tmpVideoUrl;
  56. var tmpCoverUrl = me.data.videoParams.tmpCoverUrl;
  57.  
  58. //上传短视频
  59. wx.showLoading({
  60. title: '上传中...',
  61. })
  62.  
  63. var serverUrl = app.serverUrl;
  64. wx.uploadFile({
  65. url: serverUrl + '/video/upload',
  66. formData: {
  67. userId: app.userInfo.id,
  68. bgmId: bgmId,
  69. desc: desc,
  70. videoSeconds: duration,
  71. videoWidth: tmpheight,
  72. videoHeight: tmpwidth,
  73. },
  74. filePath: tmpVideoUrl,
  75. name: 'file',
  76. header: {
  77. 'content-type': 'application/json' // 默认值
  78. },
  79. success: function (res) {
  80. var data = JSON.parse(res.data);
  81. wx.hideLoading();
  82. if (data.status == 200) {
  83.  
  84. wx.showToast({
  85. title: '上传成功!',
  86. icon: "success"
  87. });
  88. // 上传成功后跳回之前的页面
  89. wx.navigateBack({
  90. delta: 1
  91. })
  92. /*
  93. var videoId = data.data;
  94.  
  95. //上传短视频封面
  96. wx.showLoading({
  97. title: '上传中...',
  98. })
  99. wx.uploadFile({
  100. url: serverUrl + '/video/uploadCover',
  101. formData: {
  102. userId: app.userInfo.id,
  103. videoId: videoId
  104. },
  105. filePath: tmpCoverUrl,
  106. name: 'file',
  107. header: {
  108. 'content-type': 'application/json' // 默认值
  109. },
  110. success: function (res) {
  111. var data = JSON.parse(res.data);
  112. wx.hideLoading();
  113. if (data.status == 200) {
  114. wx.showToast({
  115. title: '上传成功',
  116. icon: "success"
  117. });
  118. wx.navigateBack({
  119. delta:1,
  120. })
  121. } else {
  122. wx.showToast({
  123. title: '上传失败!',
  124. icon: "success"
  125. });
  126. }
  127. }
  128. })
  129.  
  130. */
  131.  
  132. }else{
  133. wx.showToast({
  134. title: '上传失败!',
  135. icon:"success"
  136. });
  137. }
  138. }
  139. })
  140.  
  141. }
  142.  
  143. })

chooseBGM.js

微信小程序_(校园视)开发上传视频业务的更多相关文章

  1. 微信小程序_(校园视)开发视频的展示页_上

    微信小程序_(校园视) 开发用户注册登陆 传送门 微信小程序_(校园视) 开发上传视频业务 传送门 微信小程序_(校园视) 开发视频的展示页-上 传送门 微信小程序_(校园视) 开发视频的展示页-下 ...

  2. 微信小程序_(校园视)开发视频的展示页_下

    微信小程序_(校园视) 开发用户注册登陆 传送门 微信小程序_(校园视) 开发上传视频业务 传送门 微信小程序_(校园视) 开发视频的展示页-上 传送门 微信小程序_(校园视) 开发视频的展示页-下 ...

  3. 微信小程序_(校园视)开发用户注册登陆

    微信小程序_(校园视) 开发用户注册登陆 传送门 微信小程序_(校园视) 开发上传视频业务 传送门 微信小程序_(校园视) 开发视频的展示页-上 传送门 微信小程序_(校园视) 开发视频的展示页-下 ...

  4. 微信小程序环境下将文件上传到 OSS

    步骤 1: 配置 Bucket 跨域 客户端进行表单直传到 OSS 时,会从浏览器向 OSS 发送带有 Origin 的请求消息.OSS 对带有 Origin 头的请求消息会进行跨域规则(CORS)的 ...

  5. 微信小程序 springboot nginx 做图片存储 上传 浏览

    微信小程序前端-springboot后端-nginx图片存储 前言 本人小白一名,这是第一次学习微信小程序,特此做个记录. 首先准备nginx做图片存储 选择一个地址存放图片 #我的地址 [root@ ...

  6. 微信小程序踩坑日记3——上传照片至服务器

    0. 引言 主要解决将小程序端获取的图片保存在服务器上.亲测可用的服务端脚本. 1. 获取照片 通过wx.chooseImage()方法,获取到图片,使用wx.uploadFile()上传图片. wx ...

  7. 从微信小程序到鸿蒙js开发【13】——list加载更多&回到顶部

    鸿蒙入门指南,小白速来!从萌新到高手,怎样快速掌握鸿蒙开发?[课程入口] 目录: 1.list加载更多 2.list回到顶部 3.<从微信小程序到鸿蒙js开发>系列文章合集 1.list加 ...

  8. 微信小程序购物商城系统开发系列-目录结构

    上一篇我们简单介绍了一下微信小程序的IDE(微信小程序购物商城系统开发系列-工具篇),相信大家都已经蠢蠢欲试建立一个自己的小程序,去完成一个独立的商城网站. 先别着急我们一步步来,先尝试下写一个自己的 ...

  9. 微信小程序购物商城系统开发系列-工具篇

    微信小程序开放公测以来,一夜之间在各种技术社区中就火起来啦.对于它 估计大家都不陌生了,对于它未来的价值就不再赘述,简单一句话:可以把小程序简单理解为一个新的操作系统.新的生态,未来大部分应用场景都将 ...

随机推荐

  1. 【原创】大数据基础之ETL vs ELT or DataWarehouse vs DataLake

    ETL ETL is an abbreviation of Extract, Transform and Load. In this process, an ETL tool extracts the ...

  2. 【原创】大叔经验分享(60)hive和spark读取kudu表

    从impala中创建kudu表之后,如果想从hive或spark sql直接读取,会报错: Caused by: java.lang.ClassNotFoundException: com.cloud ...

  3. 非常有用的pointer-events属性

    介绍 pointer-events是css3的一个属性,指定在什么情况下元素可以成为鼠标事件的target(包括鼠标的样式) 属性值 pointer-events属性有很多值,但是对于浏览器来说,只有 ...

  4. Centos7:ActiveMQ安装,配置及使用

    解压缩ActiveMQ 的压缩包 使用 命令在bin目录下 ./activemq stat//开启 ./activemq stop//关闭 ./activemq status//状态 进入管理后台 U ...

  5. 简单聊聊服务发现(redis, zk,etcd, consul)(转载)

    服务发现并没有怎样的高深莫测,它的原理再简单不过.只是市面上太多文章将服务发现的难度妖魔化,读者被绕的云里雾里,顿觉自己智商低下不敢高攀. 服务提供者是什么,简单点说就是一个HTTP服务器,提供了AP ...

  6. BAT面试笔试33题:JavaList、Java Map等经典面试题!答案汇总!

    JavaList面试题汇总 1.List集合:ArrayList.LinkedList.Vector等. 2.Vector是List接口下线程安全的集合. 3.List是有序的. 4.ArrayLis ...

  7. 工作总结 [ActionName("ss123")] 更改路由中Action名称 获取或设置操作的名称

  8. 【转】float与double的范围和精度

    原文:http://blog.csdn.net/wuna66320/article/details/1691734 1 范围 float和double的范围是由指数的位数来决定的. float的指数位 ...

  9. VM12及CentOS-6.10的安装

    VM12的安装破解步骤 1:打开VMware 12安装界面后,点击[下一步]2:勾选[我接受许可协议中的条款]安装VMware Workstation 12 ,然后点击[下一步]3:修改默认安装路径, ...

  10. 7.控制计划任务crontab命令

    at 命令是针对仅运行一次的任务,循环运行的例行性计划任务,linux系统则是由 cron (crond) 这个系统服务来控制的Linux 系统上面原本就有非常多的计划 性工作,因此这个系统服务是默认 ...