「小程序JAVA實戰」小程序頭像圖片上傳(上)(43)

在微信小程序中,有很多的場景是用來上傳圖片的,有的圖片是拍攝獲得,有的直接選擇手機端的相冊。源碼:https://github.com/limingios/wxProgram.git 中No.15

官方組件的介紹

  • 圖片選擇API

官方網站:https://developers.weixin.qq.com/miniprogram/dev/api/media-picture.html

  • 文件上傳API
    > 官方網站:https://developers.weixin.qq.com/miniprogram/dev/api/network-file.html

增加頭像的點擊事件

<view>

  <view class='container'>
      <image src="{{faceUrl}}" class="face" bindtap='uploadFace'></image>
    <label class='nickname'>{{nickname}}</label>
      <button size='mini' class='primary' bindtap='uploadVideo'> 上傳作品</button>
      <button size='mini' type='' class='logout' bindtap='logout'>註銷</button>

        <button size='mini' type='' class='follow' data-followType='0' bindtap='followMe'>已關注</button>

        <button size='mini' type='primary' class='follow' data-followType='1' bindtap='followMe'>關注我</button>


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

// pages/mine/mine.js
const app = getApp()
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    faceUrl: "../../resource/images/noneface.png",
    nickname: "暱稱",
    fansCounts: 0,
    followCounts: 0,
    receiveLikeCounts: 0,
  },
  /**
   * 用戶註銷
   */
  logout:function(e){
    var user = app.userInfo;
    wx.showLoading({
      title: '正在註銷中。。。'
    });
    wx.request({
      url: app.serverUrl + "/logout?userId="+user.id,
      method: "POST",
      header: {
        'content-type': 'application/json' // 默認值
      },
      success: function (res) {
        console.log(res.data);
        var status = res.data.status;
        wx.hideLoading();
        if (status == 200) {
          wx.showToast({
            title: "用戶註銷成功~!",
            icon: 'none',
            duration: 3000
          })
          app.userInfo = null;
          wx.redirectTo({
            url: '../userRegister/userRegister',
          })

        } else if (status == 500) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 3000
          })
        }
      }
    })
  },
  /**
   * 頭像上傳
   */
  uploadFace:function(e){
    var user = app.userInfo;
    var me = this;
    wx.chooseImage({
      count: 1, // 默認9
      sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
      sourceType: ['camera'], // 可以指定來源是相冊還是相機,默認二者都有
      success: function (res) {
        // 返回選定照片的本地文件路徑列表,tempFilePath可以作爲img標籤的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths
        if (tempFilePaths.length>0){
          console.log(tempFilePaths[0]);
              wx.uploadFile({
                url: app.serverUrl + "/user/uploadFace?userId=" + user.id, //僅爲示例,非真實的接口地址
                filePath: tempFilePaths[0],
                name: 'file',
                success: function (res) {
                  var data = JSON.parse(res.data);
                  console.log(data);
                   wx.hideLoading();
                  if (data.status == 200) {
                    wx.showToast({
                      title: "用戶上傳成功~!",
                      icon: 'none',
                      duration: 3000
                    })
                    me.setData({
                      faceUrl: app.serverUrl+data.data
                    })


                  } else if (data.status == 500) {
                    wx.showToast({
                      title: data.msg,
                      icon: 'none',
                      duration: 3000
                    })
                  }
                }
              })
        }

      }
    })
  },
  /**
   * 生命週期函數--監聽頁面加載
   */
  onLoad: function (options) {

  },

  /**
   * 生命週期函數--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命週期函數--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命週期函數--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函數--監聽頁面卸載
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函數--監聽用戶下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function () {

  },

  /**
   * 用戶點擊右上角分享
   */
  onShareAppMessage: function () {

  }
})

後端spring boot文件的處理

增加文件上傳的工具類,時刻要記住我們是代碼的搬運工,不是代碼的製造者。能用現成的工具,絕對不手動開發一個。

  • common中
    FileUtil.java

package com.idig8.utils.file;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;
import javax.imageio.ImageIO;

import com.idig8.utils.file.enums.FileEnum;

    public class FileUtil {
         public static String uploadFile(byte[] file, String filePath, String fileName) throws Exception {
            String newDir = getDirAndDateDir(fileName);
            File targetFile = new File(filePath + newDir);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(filePath + newDir + fileName);
            out.write(file);
            out.flush();
            out.close();
            return newDir + fileName;
        }

        // 物理刪除;
        public static boolean deleteFile(String fileName) {
            File file = new File(fileName);
            // 如果文件路徑所對應的文件存在,並且是一個文件,則直接刪除
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }




        public static String renameToUUID(String fileName) {
            return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
        }

        public static String renameToUUID() {
            return UUID.randomUUID().toString();
        }

        public static boolean isImage(InputStream inputStream) throws IOException {
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            if(bufferedImage == null) {
                return false;
            }
            return true;
        }

        public static boolean isImage(File file) throws IOException {
            BufferedImage bufferedImage = ImageIO.read(file);
            if(bufferedImage == null) {
                return false;
            }
            return true;
        }


        public static String getDirAndDateDir(String fileName){
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String dir = "";
            for (FileEnum f : FileEnum.values()) {
                if(suffix.equals(f.getSuffix())){
                    dir = f.getDir();
                }
            }
            Calendar now = Calendar.getInstance();
            int year = now.get(Calendar.YEAR);
            int month = now.get(Calendar.MONTH) + 1;
            int day = now.get(Calendar.DAY_OF_MONTH);
            String dateTime = year+"-"+month+"-"+day;
            return dir+"/"+dateTime+"/";
        }
}

  • api 增加java類

package com.idig8.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
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.idig8.service.UserService;
import com.idig8.utils.JSONResult;
import com.idig8.utils.file.FileUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value="用戶接口",tags={"用戶的controller"})
@RequestMapping(value = "/user")
public class UserController extends BasicController{

    @Autowired
    private UserService userService;

    @Value("${server.face.path}")
    private String fileSpace;

    @ApiOperation(value="用戶上傳頭像",notes="用戶上傳頭像的接口")


    @ApiImplicitParams({
        @ApiImplicitParam(name="userId",value="用戶id",required=true,dataType="String",paramType="query"),
        @ApiImplicitParam(name="file",value="文件上傳",required=true,dataType="String",paramType="query"),
    })
    @PostMapping("/uploadFace")
    public JSONResult uploadFace(String userId,@RequestParam("file") MultipartFile file) {
        if (StringUtils.isBlank(userId)) {
            return JSONResult.errorMsg("用戶id不能爲空...");
        }

        // 文件保存的命名空間
        String fileName = file.getOriginalFilename();
        // 保存到數據庫中的相對路徑
         try {
                FileUtil.uploadFile(file.getBytes(), fileSpace, fileName);
            } catch (Exception e) {
                e.getStackTrace();
                return JSONResult.errorMsg(e.getMessage());
            }


        return JSONResult.ok();
    }


}

另外需要注意的是:在controller裏面我增加了一個讀配置文件裏面屬性的參數。 @Value(“${server.face.path}”)

  • 上傳後的路徑

PS:基本頭像上傳已經完畢,主要是springboot和小微信API的使用。對於用戶表中的頭像更新和交互式彈框,我後來都在源碼上做了升級。建議觀看源碼。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章