1. 程式人生 > >小程序短視頻項目———開發用戶信息之用戶上傳頭像

小程序短視頻項目———開發用戶信息之用戶上傳頭像

ability throw none 狀態 The 屬性 png .get 獲取

一、後端用戶頭像上傳接口開發

新建UsersController,用來開發與用戶相關的業務

package com.imooc.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
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.imooc.pojo.Users; import com.imooc.pojo.vo.UsersVo; import com.imooc.service.UserService; import com.imooc.utils.IMoocJSONResult; import com.imooc.utils.MD5Utils; 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 IMoocJSONResult uploadFace(String userId, @RequestParam("file") MultipartFile[] files) throws Exception { //文件保存的空間 String fileSpace = "D:/imooc_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.isNoneBlank(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); } } } catch (Exception e) { e.printStackTrace(); }finally { if(fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } return IMoocJSONResult.ok(); } }

二、小程序界面與後端用戶上傳頭像聯調

1、微信圖片選中

wx.chooseImage(Object object)

從本地相冊選擇圖片或使用相機拍照。

參數

Object object
屬性類型默認值是否必填說明支持版本
count number 9 最多可以選擇的圖片張數
sizeType Array.<string> [‘original‘, ‘compressed‘] 所選的圖片的尺寸
sourceType Array.<string> [‘album‘, ‘camera‘] 選擇圖片的來源
success function 接口調用成功的回調函數
fail function 接口調用失敗的回調函數
complete function 接口調用結束的回調函數(調用成功、失敗都會執行)

object.sizeType 的合法值

說明
original 原圖
compressed 壓縮圖

object.sourceType 的合法值

說明
album 從相冊選圖
camera 使用相機
object.success 回調函數

參數

Object res

屬性類型說明支持版本
tempFilePaths Array.<string> 圖片的本地臨時文件路徑列表
tempFiles Array.<Object> 圖片的本地臨時文件列表 >= 1.2.0

res.tempFiles 的結構

屬性類型說明支持版本
path string 本地臨時文件路徑
size number 本地臨時文件大小,單位 B

示例代碼

wx.chooseImage({
  count: 1,
  sizeType: [‘original‘, ‘compressed‘],
  sourceType: [‘album‘, ‘camera‘],
  success (res) {
    // tempFilePath可以作為img標簽的src屬性顯示圖片
    const tempFilePaths = res.tempFilePaths
  }
})

2、微信圖片上傳

UploadTask wx.uploadFile(Object object)

將本地資源上傳到開發者服務器,客戶端發起一個 HTTPS POST 請求,其中 content-typemultipart/form-data。使用前請註意閱讀相關說明。

參數

Object object
屬性類型默認值是否必填說明支持版本
url string 開發者服務器地址
filePath string 要上傳文件資源的路徑
name string 文件對應的 key,開發者在服務端可以通過這個 key 獲取文件的二進制內容
header Object HTTP 請求 Header,Header 中不能設置 Referer
formData Object HTTP 請求中其他額外的 form data
success function 接口調用成功的回調函數
fail function 接口調用失敗的回調函數
complete function 接口調用結束的回調函數(調用成功、失敗都會執行)
object.success 回調函數

參數

Object res

屬性類型說明支持版本
data string 開發者服務器返回的數據
statusCode number 開發者服務器返回的 HTTP 狀態碼

返回值

UploadTask

支持版本 >= 1.4.0

一個可以監聽上傳進度進度變化的事件和取消上傳的對象

示例代碼

wx.chooseImage({
  success (res) {
    const tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: ‘https://example.weixin.qq.com/upload‘, //僅為示例,非真實的接口地址
      filePath: tempFilePaths[0],
      name: ‘file‘,
      formData: {
        ‘user‘: ‘test‘
      },
      success (res){
        const data = res.data
        //do something
      }
    })
  }
})

3、mine.js文件更改頭像事件編寫

changeFace: function(){
    wx.chooseImage({
      count: 1,
      sizeType: [ ‘compressed‘],
      sourceType: [‘album‘],
      success(res) {
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);

        wx.showLoading({
          title: ‘Loading...‘,
        })


        var serverUrl = app.serverUrl;
        wx.uploadFile({
          url: serverUrl + ‘/user/uploadFace?userId=‘ + app.userInfo.id,
          filePath: tempFilePaths[0],
          name: ‘file‘,
          header: {
            ‘content-type‘: ‘application/json‘ // 默認值
          },
          success(res) {
            var data = res.data
            console.log(data);
            wx.hideLoading();
            wx.showToast({
              title: ‘success‘,
              icon: "success"
            })
          }
        })


      }
    })
  }

三、上傳頭像後更新到數據庫

技術分享圖片

userServiceImpl

技術分享圖片

UserController

技術分享圖片

四、完整的前端js

 changeFace: function(){
    var me = this;
    wx.chooseImage({
      count: 1,
      sizeType: [ ‘compressed‘],
      sourceType: [‘album‘],
      success(res) {
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);

        wx.showLoading({
          title: ‘Loading...‘,
        })


        var serverUrl = app.serverUrl;
        wx.uploadFile({
          url: serverUrl + ‘/user/uploadFace?userId=‘ + app.userInfo.id,
          filePath: tempFilePaths[0],
          name: ‘file‘,
          header: {
            ‘content-type‘: ‘application/json‘ // 默認值
          },
          success(res) {
            var data = JSON.parse(res.data);
            console.log(data);
            wx.hideLoading();
            if (data.status == 200) {
              wx.showToast({
                title: ‘success‘,
                icon: "success"
              });
              var imageUrl = data.data;
              me.setData({
                faceUrl: serverUrl + imageUrl
              })


            }else if (data.status == 500){
              wx.showToast({
                title: data.msg,
              })
            }
            
          }
        })

      }
    })
  }

小程序短視頻項目———開發用戶信息之用戶上傳頭像