1. 程式人生 > >【java小程式】小程式視訊上傳檔案的前後端程式碼

【java小程式】小程式視訊上傳檔案的前後端程式碼

文章目錄


上傳小視訊功能,我們是通過我的主頁點選上傳按鈕進行上傳,選中視訊後會獲取視訊的一些資料,通過跳轉頁面連結傳遞值。

小程式端程式碼

1、上傳視訊選中事件

1) wx.chooseVideo 是小程式中的視訊選擇API。
2)選中視訊success返回視訊的長度、高度、寬度、臨時地址、臨時封面圖等
3) wx.navigateTo 進行頁面跳轉的API,將視訊資料傳遞到背景音樂選擇頁。

  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
            })
          }
        }
      })
    }

2、背景音樂的頁面載入

點選此處檢視選擇背景音樂的相關頁面渲染程式碼,這裡只對上傳事件請求進行闡述。

  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多個註解括起來。

@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();
    }


}