这篇博客主要是wx.chooseImage(Object object)及UploadTask wx.uploadFile(Object object)的实战案例
官方网址:
https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html
https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html
Mine.wxss
page { font-size: 14px; } .container { background-color: whitesmoke; display: flex; flex-direction: column; align-items: center; } .container-row { display: flex; flex-direction: row; margin-bottom: 10px; margin-top: 10px; } .info-items { margin-left: 30px; } .face { width: 180rpx; height: 180rpx; border-radius: 50%; margin-top: 20px; } .nickname { margin-top: 5px; font-weight: bold; font-size: 18px; } .logout { margin-top: 3px; float: right; } .follow { margin-top: 3px; } .line { width: 100%; height: 1px; background-color: gainsboro; margin-top: 1px; } .container-video { display: flex; flex-direction: row; margin-top: 20px; text-align: center; border: solid 1px; line-height: 30px; } .video-info { width: 100%; } .video-info-selected { background-color: gainsboro; } .container-video-list { display: flex; flex-direction: row; flex-wrap: wrap; } .videoImage { width: 250rpx; height: 180px; }
Mine.wxml
<view> <view class='container'> <block wx:if="{{isMe}}"> <image src="{{faceUrl}}" class="face" bindtap='changeFace'></image> </block> <block wx:if="{{!isMe}}"> <image src="{{faceUrl}}" class="face"></image> </block> <label class='nickname'>{{nickname}}</label> <block wx:if="{{isMe}}"> <button size='mini' class='primary' bindtap='uploadVideo'> 上传作品</button> <button size='mini' type='' class='logout' bindtap='logout'>注销</button> </block> <block wx:if="{{!isMe}}"> <block wx:if="{{isFollow}}"> <button size='mini' type='' class='follow' data-followType='0' bindtap='followMe'>已关注</button> </block> <block wx:if="{{!isFollow}}"> <button size='mini' type='primary' class='follow' data-followType='1' bindtap='followMe'>关注我</button> </block> </block> <view class='container-row'> <label class='info-items'>{{fansCounts}} 粉丝</label> <label class='info-items'>{{followCounts}} 关注</label> <label class='info-items'>{{receiveLikeCounts}} 获赞</label> </view> </view> </view> <view class="line"></view> <view class='container-video'> <!-- 发布过的作品 --> <view class='{{videoSelClass}} {{isSelectedWork}}' bindtap='doSelectWork'>作品</view> <!-- 收藏的点赞的视频 --> <view class='{{videoSelClass}} {{isSelectedLike}}' bindtap='doSelectLike'>收藏</view> <!-- 用户关注过人发表的视频 --> <view class='{{videoSelClass}} {{isSelectedFollow}}' bindtap='doSelectFollow'>关注</view> </view> <view class='container-video-list'> <view hidden='{{myWorkFalg}}'> <block wx:for="{{myVideoList}}" > <image src='{{serverUrl}}{{item.coverPath}}' class='videoImage' mode="aspectFill" bindtap='showVideo' data-arrindex='{{index}}'></image> </block> </view> <view hidden='{{myLikesFalg}}'> <block wx:for="{{likeVideoList}}" > <image src='{{serverUrl}}{{item.coverPath}}' class='videoImage' mode="aspectFill" bindtap='showVideo' data-arrindex='{{index}}'></image> </block> </view> <view hidden='{{myFollowFalg}}'> <block wx:for="{{followVideoList}}" > <image src='{{serverUrl}}{{item.coverPath}}' class='videoImage' mode="aspectFill" bindtap='showVideo' data-arrindex='{{index}}'></image> </block> </view> </view>
Mine.js
var videoUtil = require('../../utils/videoUtil.js') const app = getApp() Page({ /** * 页面的初始数据 */ data: { faceUrl: "../resource/images/noneface.png", isMe: true, isFollow: false, videoSelClass: "video-info", isSelectedWork: "video-info-selected", isSelectedLike: "", isSelectedFollow: "", myVideoList: [], myVideoPage: 1, myVideoTotal: 1, likeVideoList: [], likeVideoPage: 1, likeVideoTotal: 1, followVideoList: [], followVideoPage: 1, followVideoTotal: 1, myWorkFalg: false, myLikesFalg: true, myFollowFalg: true }, /** * 生命周期函数--监听页面加载 */ onLoad: function (params) { var me = this; // var user = app.userInfo; // fixme 修改原有的全局对象为本地缓存 var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = params.publisherId; if (publisherId != null && publisherId != '' && publisherId != undefined) { userId = publisherId; me.setData({ isMe: false, publisherId: publisherId, serverUrl: app.serverUrl }) } me.setData({ userId: userId }) wx.showLoading({ title: '请等待...', }); var serverUrl = app.serverUrl; // 调用后端 wx.request({ url: serverUrl + '/user/query?userId=' + userId + "&fanId=" + user.id, method: "POST", header: { 'content-type': 'application/json', // 默认值 'headerUserId': user.id, 'headerUserToken': user.userToken }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { var userInfo = res.data.data; var faceUrl = "../resource/images/noneface.png"; if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage != undefined) { faceUrl = serverUrl + userInfo.faceImage; } me.setData({ faceUrl: faceUrl, fansCounts: userInfo.fansCounts, followCounts: userInfo.followCounts, receiveLikeCounts: userInfo.receiveLikeCounts, nickname: userInfo.nickname, isFollow: userInfo.follow }); } else if (res.data.status == 502) { wx.showToast({ title: res.data.msg, duration: 3000, icon: "none", success: function () { wx.redirectTo({ url: '../userLogin/login', }) } }) } } }) // me.getMyVideoList(1); }, followMe: function (e) { var me = this; var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = me.data.publisherId; var followType = e.currentTarget.dataset.followtype; // 1:关注 0:取消关注 var url = ''; if (followType == '1') { url = '/user/beyourfans?userId=' + publisherId + '&fanId=' + userId; } else { url = '/user/dontbeyourfans?userId=' + publisherId + '&fanId=' + userId; } wx.showLoading(); wx.request({ url: app.serverUrl + url, method: 'POST', header: { 'content-type': 'application/json', // 默认值 'headerUserId': user.id, 'headerUserToken': user.userToken }, success: function () { wx.hideLoading(); if (followType == '1') { me.setData({ isFollow: true, fansCounts: ++me.data.fansCounts }) } else { me.setData({ isFollow: false, fansCounts: --me.data.fansCounts }) } } }) }, logout: function () { // var user = app.userInfo; var user = app.getGlobalUserInfo(); var serverUrl = app.serverUrl; wx.showLoading({ title: '请等待...', }); // 调用后端 wx.request({ url: serverUrl + '/logout?userId=' + user.id, method: "POST", header: { 'content-type': 'application/json' // 默认值 }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { // 登录成功跳转 wx.showToast({ title: '注销成功', icon: 'success', duration: 2000 }); // app.userInfo = null; // 注销以后,清空缓存 wx.removeStorageSync("userInfo") // 页面跳转 wx.redirectTo({ url: '../userLogin/login', }) } } }) }, changeFace: function () { var me = this; wx.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['album'], success: function (res) { var tempFilePaths = res.tempFilePaths; console.log(tempFilePaths); wx.showLoading({ title: '上传中...', }) var serverUrl = app.serverUrl; // fixme 修改原有的全局对象为本地缓存 var userInfo = app.getGlobalUserInfo(); wx.uploadFile({ url: serverUrl + '/user/uploadFace?userId=' + userInfo.id, //app.userInfo.id, filePath: tempFilePaths[0], name: 'file', header: { 'content-type': 'application/json', // 默认值 'headerUserId': userInfo.id, 'headerUserToken': userInfo.userToken }, success: function (res) { var data = JSON.parse(res.data); console.log(data); wx.hideLoading(); if (data.status == 200) { wx.showToast({ title: '上传成功!~~', icon: "success" }); var imageUrl = data.data; me.setData({ faceUrl: serverUrl + imageUrl }); } else if (data.status == 500) { wx.showToast({ title: data.msg }); } else if (res.data.status == 502) { wx.showToast({ title: res.data.msg, duration: 2000, icon: "none", success: function () { wx.redirectTo({ url: '../userLogin/login', }) } }); } } }) } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
所需后端代码
UserController.java
package com.javaxl.controller; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.javaxl.pojo.Users; import com.javaxl.pojo.UsersReport; import com.javaxl.pojo.vo.PublisherVideo; import com.javaxl.pojo.vo.UsersVO; import com.javaxl.service.UserService; import com.javaxl.utils.JSONResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; @RestController @Api(value="用户相关业务的接口", tags= {"用户相关业务的controller"}) @RequestMapping("/user") public class UserController extends BasicController { @Autowired private UserService userService; @ApiOperation(value="用户上传头像", notes="用户上传头像的接口") @ApiImplicitParam(name="userId", value="用户id", required=true, dataType="String", paramType="query") @PostMapping("/uploadFace") public JSONResult uploadFace(String userId, @RequestParam("file") MultipartFile[] files) throws Exception { if (StringUtils.isBlank(userId)) { return JSONResult.errorMsg("用户id不能为空..."); } // 文件保存的命名空间 String fileSpace = "C:/javaxl_videos_dev"; // 保存到数据库中的相对路径 String uploadPathDB = "/" + userId + "/face"; FileOutputStream fileOutputStream = null; InputStream inputStream = null; try { if (files != null && files.length > 0) { String fileName = files[0].getOriginalFilename(); if (StringUtils.isNotBlank(fileName)) { // 文件上传的最终保存路径 String finalFacePath = fileSpace + uploadPathDB + "/" + fileName; // 设置数据库保存的路径 uploadPathDB += ("/" + fileName); File outFile = new File(finalFacePath); if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) { // 创建父文件夹 outFile.getParentFile().mkdirs(); } fileOutputStream = new FileOutputStream(outFile); inputStream = files[0].getInputStream(); IOUtils.copy(inputStream, fileOutputStream); } } else { return JSONResult.errorMsg("上传出错..."); } } catch (Exception e) { e.printStackTrace(); return JSONResult.errorMsg("上传出错..."); } finally { if (fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } Users user = new Users(); user.setId(userId); user.setFaceImage(uploadPathDB); userService.updateUserInfo(user); return JSONResult.ok(uploadPathDB); } @ApiOperation(value="查询用户信息", notes="查询用户信息的接口") @ApiImplicitParam(name="userId", value="用户id", required=true, dataType="String", paramType="query") @PostMapping("/query") public JSONResult query(String userId, String fanId) throws Exception { if (StringUtils.isBlank(userId)) { return JSONResult.errorMsg("用户id不能为空..."); } Users userInfo = userService.queryUserInfo(userId); UsersVO userVO = new UsersVO(); BeanUtils.copyProperties(userInfo, userVO); userVO.setFollow(userService.queryIfFollow(userId, fanId)); return JSONResult.ok(userVO); } @PostMapping("/queryPublisher") public JSONResult queryPublisher(String loginUserId, String videoId, String publishUserId) throws Exception { if (StringUtils.isBlank(publishUserId)) { return JSONResult.errorMsg(""); } // 1. 查询视频发布者的信息 Users userInfo = userService.queryUserInfo(publishUserId); UsersVO publisher = new UsersVO(); BeanUtils.copyProperties(userInfo, publisher); // 2. 查询当前登录者和视频的点赞关系 boolean userLikeVideo = userService.isUserLikeVideo(loginUserId, videoId); PublisherVideo bean = new PublisherVideo(); bean.setPublisher(publisher); bean.setUserLikeVideo(userLikeVideo); return JSONResult.ok(bean); } @PostMapping("/beyourfans") public JSONResult beyourfans(String userId, String fanId) throws Exception { if (StringUtils.isBlank(userId) || StringUtils.isBlank(fanId)) { return JSONResult.errorMsg(""); } userService.saveUserFanRelation(userId, fanId); return JSONResult.ok("关注成功..."); } @PostMapping("/dontbeyourfans") public JSONResult dontbeyourfans(String userId, String fanId) throws Exception { if (StringUtils.isBlank(userId) || StringUtils.isBlank(fanId)) { return JSONResult.errorMsg(""); } userService.deleteUserFanRelation(userId, fanId); return JSONResult.ok("取消关注成功..."); } @PostMapping("/reportUser") public JSONResult reportUser(@RequestBody UsersReport usersReport) throws Exception { // 保存举报信息 userService.reportUser(usersReport); return JSONResult.errorMsg("举报成功...有你平台变得更美好..."); } }
VideoController.java
package com.javaxl.controller; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Date; import java.util.UUID; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.javaxl.enums.VideoStatusEnum; import com.javaxl.pojo.Bgm; import com.javaxl.pojo.Comments; import com.javaxl.pojo.Videos; import com.javaxl.service.BgmService; import com.javaxl.service.VideoService; import com.javaxl.utils.FetchVideoCover; import com.javaxl.utils.JSONResult; import com.javaxl.utils.MergeVideoMp3; import com.javaxl.utils.PagedResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @RestController @Api(value="视频相关业务的接口", tags= {"视频相关业务的controller"}) @RequestMapping("/video") public class VideoController extends BasicController { @Autowired private BgmService bgmService; @Autowired private VideoService videoService; @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="String", paramType="form"), @ApiImplicitParam(name="videoWidth", value="视频宽度", required=true, dataType="String", paramType="form"), @ApiImplicitParam(name="videoHeight", value="视频高度", required=true, dataType="String", paramType="form"), @ApiImplicitParam(name="desc", value="视频描述", required=false, dataType="String", paramType="form") }) @PostMapping(value="/upload", headers="content-type=multipart/form-data") public JSONResult upload(String userId, String bgmId, double videoSeconds, int videoWidth, int videoHeight, String desc, @ApiParam(value="短视频", required=true) MultipartFile file) throws Exception { if (StringUtils.isBlank(userId)) { return JSONResult.errorMsg("用户id不能为空..."); } // 文件保存的命名空间 // String fileSpace = "C:/javaxl_videos_dev"; // 保存到数据库中的相对路径 String uploadPathDB = "/" + userId + "/video"; String coverPathDB = "/" + userId + "/video"; FileOutputStream fileOutputStream = null; InputStream inputStream = null; // 文件上传的最终保存路径 String finalVideoPath = ""; try { if (file != null) { String fileName = file.getOriginalFilename(); // abc.mp4 String arrayFilenameItem[] = fileName.split("\\."); String fileNamePrefix = ""; for (int i = 0 ; i < arrayFilenameItem.length-1 ; i ++) { fileNamePrefix += arrayFilenameItem[i]; } // fix bug: 解决小程序端OK,PC端不OK的bug,原因:PC端和小程序端对临时视频的命名不同 // String fileNamePrefix = fileName.split("\\.")[0]; if (StringUtils.isNotBlank(fileName)) { finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName; // 设置数据库保存的路径 uploadPathDB += ("/" + fileName); coverPathDB = coverPathDB + "/" + fileNamePrefix + ".jpg"; File outFile = new File(finalVideoPath); if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) { // 创建父文件夹 outFile.getParentFile().mkdirs(); } fileOutputStream = new FileOutputStream(outFile); inputStream = file.getInputStream(); IOUtils.copy(inputStream, fileOutputStream); } } else { return JSONResult.errorMsg("上传出错..."); } } catch (Exception e) { e.printStackTrace(); return JSONResult.errorMsg("上传出错..."); } finally { if (fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } // 判断bgmId是否为空,如果不为空, // 那就查询bgm的信息,并且合并视频,生产新的视频 if (StringUtils.isNotBlank(bgmId)) { Bgm bgm = bgmService.queryBgmById(bgmId); String mp3InputPath = FILE_SPACE + bgm.getPath(); MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE); String videoInputPath = finalVideoPath; String videoOutputName = UUID.randomUUID().toString() + ".mp4"; uploadPathDB = "/" + userId + "/video" + "/" + videoOutputName; finalVideoPath = FILE_SPACE + uploadPathDB; tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath); } System.out.println("uploadPathDB=" + uploadPathDB); System.out.println("finalVideoPath=" + finalVideoPath); // 对视频进行截图 FetchVideoCover videoInfo = new FetchVideoCover(FFMPEG_EXE); videoInfo.getCover(finalVideoPath, FILE_SPACE + coverPathDB); // 保存视频信息到数据库 Videos video = new Videos(); video.setAudioId(bgmId); video.setUserId(userId); video.setVideoSeconds((float)videoSeconds); video.setVideoHeight(videoHeight); video.setVideoWidth(videoWidth); video.setVideoDesc(desc); video.setVideoPath(uploadPathDB); video.setCoverPath(coverPathDB); video.setStatus(VideoStatusEnum.SUCCESS.value); video.setCreateTime(new Date()); String videoId = videoService.saveVideo(video); return JSONResult.ok(videoId); } @ApiOperation(value="上传封面", notes="上传封面的接口") @ApiImplicitParams({ @ApiImplicitParam(name="userId", value="用户id", required=true, dataType="String", paramType="form"), @ApiImplicitParam(name="videoId", value="视频主键id", required=true, dataType="String", paramType="form") }) @PostMapping(value="/uploadCover", headers="content-type=multipart/form-data") public JSONResult uploadCover(String userId, String videoId, @ApiParam(value="视频封面", required=true) MultipartFile file) throws Exception { if (StringUtils.isBlank(videoId) || StringUtils.isBlank(userId)) { return JSONResult.errorMsg("视频主键id和用户id不能为空..."); } // 文件保存的命名空间 // String fileSpace = "C:/javaxl_videos_dev"; // 保存到数据库中的相对路径 String uploadPathDB = "/" + userId + "/video"; FileOutputStream fileOutputStream = null; InputStream inputStream = null; // 文件上传的最终保存路径 String finalCoverPath = ""; try { if (file != null) { String fileName = file.getOriginalFilename(); if (StringUtils.isNotBlank(fileName)) { finalCoverPath = FILE_SPACE + uploadPathDB + "/" + fileName; // 设置数据库保存的路径 uploadPathDB += ("/" + fileName); File outFile = new File(finalCoverPath); if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) { // 创建父文件夹 outFile.getParentFile().mkdirs(); } fileOutputStream = new FileOutputStream(outFile); inputStream = file.getInputStream(); IOUtils.copy(inputStream, fileOutputStream); } } else { return JSONResult.errorMsg("上传出错..."); } } catch (Exception e) { e.printStackTrace(); return JSONResult.errorMsg("上传出错..."); } finally { if (fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } videoService.updateVideo(videoId, uploadPathDB); return JSONResult.ok(); } /** * * @Description: 分页和搜索查询视频列表 * isSaveRecord:1 - 需要保存 * 0 - 不需要保存 ,或者为空的时候 */ @PostMapping(value="/showAll") public JSONResult showAll(@RequestBody Videos video, Integer isSaveRecord, Integer page, Integer pageSize) throws Exception { if (page == null) { page = 1; } if (pageSize == null) { pageSize = PAGE_SIZE; } PagedResult result = videoService.getAllVideos(video, isSaveRecord, page, pageSize); return JSONResult.ok(result); } /** * @Description: 我关注的人发的视频 */ @PostMapping("/showMyFollow") public JSONResult showMyFollow(String userId, Integer page) throws Exception { if (StringUtils.isBlank(userId)) { return JSONResult.ok(); } if (page == null) { page = 1; } int pageSize = 6; PagedResult videosList = videoService.queryMyFollowVideos(userId, page, pageSize); return JSONResult.ok(videosList); } /** * @Description: 我收藏(点赞)过的视频列表 */ @PostMapping("/showMyLike") public JSONResult showMyLike(String userId, Integer page, Integer pageSize) throws Exception { if (StringUtils.isBlank(userId)) { return JSONResult.ok(); } if (page == null) { page = 1; } if (pageSize == null) { pageSize = 6; } PagedResult videosList = videoService.queryMyLikeVideos(userId, page, pageSize); return JSONResult.ok(videosList); } @PostMapping(value="/hot") public JSONResult hot() throws Exception { return JSONResult.ok(videoService.getHotwords()); } @PostMapping(value="/userLike") public JSONResult userLike(String userId, String videoId, String videoCreaterId) throws Exception { videoService.userLikeVideo(userId, videoId, videoCreaterId); return JSONResult.ok(); } @PostMapping(value="/userUnLike") public JSONResult userUnLike(String userId, String videoId, String videoCreaterId) throws Exception { videoService.userUnLikeVideo(userId, videoId, videoCreaterId); return JSONResult.ok(); } @PostMapping("/saveComment") public JSONResult saveComment(@RequestBody Comments comment, String fatherCommentId, String toUserId) throws Exception { comment.setFatherCommentId(fatherCommentId); comment.setToUserId(toUserId); videoService.saveComment(comment); return JSONResult.ok(); } @PostMapping("/getVideoComments") public JSONResult getVideoComments(String videoId, Integer page, Integer pageSize) throws Exception { if (StringUtils.isBlank(videoId)) { return JSONResult.ok(); } // 分页查询视频列表,时间顺序倒序排序 if (page == null) { page = 1; } if (pageSize == null) { pageSize = 10; } PagedResult list = videoService.getAllComments(videoId, page, pageSize); return JSONResult.ok(list); } }
结果图如下
over......
备案号:湘ICP备19000029号
Copyright © 2018-2019 javaxl晓码阁 版权所有