SpringBoot+微信小程序实现视频上传并在MySQL数据库中保存视频的存储路径
一、 视频上传在微信小程序端的代码
1.视频上传功能描述
点击视频上传按钮,选择要上传的视频,进行视频上传,显示上传进度,上传后无论是成功还是失败给出相应的反馈。
2.代码实现
(1)wxml文件代码
<view class="" data-incident="{{item.id}}" bindtap = "chooseVideo">上传视频</view>
按钮样式就自己设置啦~在这里我就不贴出了。
bindtap = “chooseVideo” 绑定chooseVideo事件,chooseVideo代码见后面js文件中。
data-incident="{{item.id}}" 给chooseVideo事件传参数,对应不同的内容需要传相应的视频,这时候就需要将视频与内容对应起来,所以需要给定内容的唯一标识。
(2)对应的js文件代码
Page({
/**
* 页面的初始数据
*/
data: {
video:'',//视频存储位置
eventid:''//视频对应的内容的唯一标识,这里是id
},
/**
* 选择视频并上传服务器
*/
chooseVideo: function (event) {
let that = this
//获取内容id
let event_id=event.currentTarget.dataset.incident
that.setData({
eventid:event_id
})
//从手机相册中选择视频
wx.chooseVideo({
sourceType: ['album'], // album 从相册选视频,camera 使用相机拍摄
compressed: true,//是否压缩所选择的视频文件
success: function(res){
//console.log(res)
let tempFilePath = res.tempFilePath//选择定视频的临时文件路径(本地路径)
let duration = res.duration //选定视频的时间长度
let size = parseFloat(res.size/1024/1024).toFixed(1) //选定视频的数据量大小
if(parseFloat(size) > 100){
let beyondSize = parseFloat(size) - 100
wx.showToast({
title: '上传的视频大小超限,超出'+beyondSize+'MB,请重新上传',
//image: '',//自定义图标的本地路径,image的优先级高于icon
icon:'none'
})
}else{
//2.本地视频资源上传到服务器
that.uploadFile(tempFilePath)
}
},
fail: function() {
// fail
},
complete: function() {
// complete
}
})
},
/**
* 将本地资源上传到服务器
*/
uploadFile:function(tempFilePath){
let that = this
let third_session = wx.getStorageSync('third_session')
wx.showLoading({
title: '上传进度:0%',
mask: true //是否显示透明蒙层,防止触摸穿透
})
const uploadTask = wx.uploadFile({
url: 'http://localhost:8080/upload/uploadVideo',//开发者服务器地址,记得换成自己对应的地址哦
filePath:tempFilePath,//要上传文件资源的路径(本地路径)
name:'file',//文件对应key,开发者在服务端可以通过这个 key 获取文件的二进制内容
formData: {
third_session: third_session
}, // HTTP 请求中其他额外的 form data
success: function(res){
console.log("uploadFile",res)
// success
console.log(that.timeout)
let data = JSON.parse(res.data)
that.setData({
video:data.videoUrl
})
//视频成功上传后将视频存储位置存储在数据库中
wx.request({
url: 'http://localhost:8080/changevideo',//后端代码接口
//choosevideo接口的参数,注意这里不能使用url传参
data:{
id:that.data.eventid,
video:data.videoUrl
},
//method设置为GET,之前设置为POST导致无法将视频存储路径保存至数据库
method: "GET",
success: function (res) {
},
fail: function (res) {
wx.showToast({
icon: 'loading',
title: '数据库访问失败'
})
}
})
wx.hideLoading()
if(data.returnCode == 200){
wx.showToast({
title: '上传成功',
icon: 'success',
})
}else{
wx.showToast({
title: '上传失败',
icon: 'none'
})
}
},
fail: function() {
// fail
wx.hideLoading()
this.setData({
videoUrl: '',
poster: '',
duration: '',
clickFlag:true
})
wx.showToast({
title: '上传失败',
icon: 'none'
})
}
})
//监听上传进度变化事件
uploadTask.onProgressUpdate((res) =>{
wx.showLoading({
title: '上传进度:'+res.progress+'%',
mask: true //是否显示透明蒙层,防止触摸穿透
})
console.log("上传进度",res.progress)
console.log("已经上传的数据长度,单位 Bytes:",res.totalBytesSent)
console.log("预期需要上传的数据总长度,单位 Bytes:",res.totalBytesExpectedToSend)
})
},
二、视频上传在服务器端的代码
(1)uploadcontroller文件
package com.example.cdc_code.Controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.cdc_code.service.UploadService;
/**
* 文件上传
*/
@RestController
@RequestMapping("/upload")
public class UploadController {
@Autowired
private UploadService uploadService;
/**
* 视频文件上传
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value ="/uploadVideo",method=RequestMethod.POST)
public Map<String, Object> uploadVideo(MultipartFile file,HttpServletRequest request) throws Exception{
return uploadService.uploadVideo(file, request);
}
}
(2)uploadServicelmpl文件
package com.example.cdc_code.service.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import com.example.cdc_code.entity.Incident;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;
import com.example.cdc_code.service.UploadService;
@Transactional
@Service("UploadService")
public class UploadServiceImpl implements UploadService{
/**
* 视频文件上传
*/
@Override
public Map<String, Object> uploadVideo(MultipartFile file,HttpServletRequest request) throws Exception {
Map<String, Object> resultMap=new HashMap<String, Object>();
String basePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort()+"/upload/video/";
Long time = new Date().getTime();
String fileName = file.getOriginalFilename();//文件原始名称
String suffixName = fileName.substring(fileName.lastIndexOf("."));//从最后一个开始截取。截取fileName的后缀名
String newFileName = time+suffixName; //文件新名称
//设置文件存储路径,可以存放在你想要指定的路径里面
String rootPath="G:/"+File.separator+"upload/video/"; //上传视频存放位置
String filePath = rootPath+newFileName;
File newFile = new File(filePath);
//判断目标文件所在目录是否存在
if(!newFile.getParentFile().exists()){
//如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
//将内存中的数据写入磁盘
file.transferTo(newFile);
//视频上传保存url
String videoUrl = basePath + newFileName;
resultMap.put("videoUrl", videoUrl);
resultMap.put("filename", newFileName);
resultMap.put("returnCode", 200);
//System.out.println("上传的文件名为:"+fileName+",后缀名为:"+newFileName);
return resultMap;
}
}