【java小程序】小程序视频上传文件的先后端代码


上传小视频功能,咱们是经过个人主页点击上传按钮进行上传,选中视频后会获取视频的一些数据,经过跳转页面连接传递值。

小程序端代码

一、上传视频选中事件

1) wx.chooseVideo 是小程序中的视频选择API。
2)选中视频success返回视频的长度、高度、宽度、临时地址、临时封面图等
3) wx.navigateTo 进行页面跳转的API,将视频数据传递到背景音乐选择页。web

uploadVideo: function(){
      var me = this;
      //微信中选择视频的api
      wx.chooseVideo({
        sourceType:['album','camera'],
        success:function (res){
          console.log(res);
          //获取视频的时间
          var duration = res.duration;
          //获取图片的高
          var height = res.height;
          //获取图片的宽
          var width = res.width;
          //获取视频的临时地址
          var tmpVideoUrl = res.tempFilePath;
          //获取视频的临时封面
          var tmpCoverUrl = res.thumbTempFilePath;
          if (duration > 16){
            wx.showToast({
              title: '视频长度不能超过15秒...',
              icon:"none",
              duration:2500
            })
          } else if (duration < 2){
            wx.showToast({
              title: '视频过短,不能上传',
              icon:"none",
              duration: 2500
            })
          } else {

            //打开选择bgm(背景音乐)的页面
            wx.navigateTo({
              url:'../choosebgm/choosebgm?duration=' + duration
              + "&tmpHeight=" + height
              + "&tmpWidth=" + width
              + "&tmpVideoUrl=" + tmpVideoUrl
              + "&tmpCoverUrl=" + tmpCoverUrl
            })
          }
        }
      })
    }

二、背景音乐的页面加载

点击此处查看选择背景音乐的相关页面渲染代码,这里只对上传事件请求进行阐述。数据库

  1. onLoad 页面第一次加载的时候执行函数。
    2)经过参数params,获取视频传递过来的数据,并进行data设置,方便使用
onLoad: function(params) {
    var me = this;
    console.log(params);
   me.setData({
      videoParams: params
   })
}
  1. 上传视频事件,wx.uploadFile 小程序提供的上传文件api
    4)formData 后台传递的数据。
  2. name 属性的值,要和后台接收的值要同样。
upload: function(e) {
    var me = this;
    var bgmId = e.detail.value.bgmId;
    var desc = e.detail.value.desc;

    var duration = me.data.videoParams.duration;
    //获取图片的高
    var tmpHeight = me.data.videoParams.tmpHeight;
    //获取图片的宽
    var tmpWidth = me.data.videoParams.tmpWidth;
    //获取视频的临时地址
    var tmpVideoUrl = me.data.videoParams.tempFilePath;
    //获取视频的临时封面地址
    var tmpCoverUrl = me.data.videoParams.thumbTempFilePath;

    //上传短视频
    wx.showLoading({
      title: '上传中...',
    })
    var serverUrl = app.serverUrl;
    wx.uploadFile({
      url: serverUrl + '/video/upload?userId=' + app.userInfo.id,
      formData:{
         userId : app.userInfo.id,
         bgmId: bgmId,
         desc: desc,
         videoSeconds: duration,
         videoHeight: tmpHeight,
         videoWidth: tmpWidth
      },
      filePath: tmpVideoUrl,
      name: 'files',
      header:{
        'content-type':'application/json'
      },
      success:function (res) {
        wx.hideLoading();
        if(res.data.status == 200){
                wx.showToast({
                  title: '上传成功!',
                  icon:"success"
                })
        }
      }
    })
  }

上传文件的后端代码

1) swagger 接口当有多个参数时,须要使用 @ApiImplicitParams 将 @ApiImplicitParam多个注解括起来。json

@Api(value = "视频相关业务接口", tags = {"视频相关业务的controller"})
@RestController
@RequestMapping("/video")
public class VideoController extends BasicController {
    @ApiOperation(value="上传视频", notes = "上传视频的接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userId",value="用户id",required = true,dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "bgmId",value="背景音乐id",required = false,dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "videoSeconds",value="上传视频播放长度",required = true,dataType = "double", paramType = "form"),
            @ApiImplicitParam(name = "videoWidth",value="上传视频的宽度",required = true,dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "videoHeight",value="上传视频的高度",required = true,dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "desc",value="上传视频的描述",required = false,dataType = "String", paramType = "form")
    })

    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public IMoocJSONResult upload(String userId, String bgmId, double videoSeconds,
                                  int videoWidth, int videoHeight, String desc,
                                  @ApiParam(value = "短视频",required = true) MultipartFile files){
        if(StringUtils.isBlank(userId)) {
            return IMoocJSONResult.errorMsg("用户id不能为空");
        }
        //保存文件的路径
        String fileSpace = "G:\\imooc-video-dev";
        //保存到数据库的相对路径
        String uploadPathDB = "\\" + userId + "\\video";
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;

        try {
        if(files != null ) {
            String fileNmae = files.getOriginalFilename();

                if (StringUtils.isNotBlank(fileNmae)) {
                    //文件上传的最终保存路径
                    String finalVideoPath = fileSpace + uploadPathDB + "\\" + fileNmae;
                    //数据库最终保存的相对路径
                    uploadPathDB += ("\\" + fileNmae);

                    File outFile = new File(finalVideoPath);
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
                        //建立父类文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = files.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
        } else {
            return  IMoocJSONResult.errorMsg("上传出错");
        }
            } catch (Exception e) {
            return  IMoocJSONResult.errorMsg("上传出错");
            } finally {
          try{
              if(fileOutputStream !=null ){
                  fileOutputStream.flush();
                  fileOutputStream.close();
              }
          } catch(IOException e){
              return IMoocJSONResult.errorMsg("上传出错");
          }
        }

        return IMoocJSONResult.ok();
    }


}