springboot2.x+小程序,實(shí)現(xiàn)小程序的頭像上傳

前段事件,學(xué)習(xí)了下springboot的一些知識(shí),現(xiàn)在復(fù)習(xí)一下,用springboot2結(jié)合小程序,實(shí)現(xiàn)一下前后端頭像上傳的功能。廢話不多說(shuō),看具體代碼,看不懂的小伙伴記得留言,我會(huì)一一解答。

springboot代碼:

public class UploadUtils {
    public static File getFileDir(String userId) {

        String filePath = "/Users/wudengyao/111111springboot_upload/";
        String childPath = userId+"/images/";

        //如果上傳目錄為/static/images/upload/,則可以如下獲取
        File upload=new File(filePath,childPath);
        if(!upload.exists()){
            upload.mkdirs();
            //在開(kāi)發(fā)測(cè)試模式時(shí),得到地址為:{項(xiàng)目跟目錄}/target/static/images/upload/
            //在打成jar正式發(fā)布時(shí),得到的地址為:{發(fā)布jar包目錄}/static/images/upload/

        }
        System.out.println(upload.getAbsolutePath());

        return upload;
    }
}
/**
     * 圖片上傳
     * @param userId
     * @param file
     * @return
     */
    @PostMapping(value ="/upload",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Object upload(String userId,@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResultUtil.fail(ResponseResultEnum.UNKNOWN.getCode(),
                    "上傳失敗,請(qǐng)選擇文件");
        }
        String fileName = file.getOriginalFilename();
        File upload = UploadUtils.getFileDir(userId);

        File dest = new File(upload,fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("上傳成功");
            System.out.println(userId+"/images/"+fileName);


            User user = new User();
            user.setId(Integer.parseInt(userId));
            user.setAvator(userId+"/images/"+fileName);
            userService.updateUser(user);

            return ResponseResultUtil.success("上傳成功",user);

        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return ResponseResultUtil.fail(ResponseResultEnum.UNKNOWN.getCode(),
                "上傳失敗");

    }

這里頭像上傳成功之后,還有一部更新數(shù)據(jù)庫(kù)用戶頭像的操作

  User user = new User();
  user.setId(Integer.parseInt(userId));
  user.setAvator(userId+"/images/"+fileName);
  userService.updateUser(user);
mapper里的sql語(yǔ)句.png
虛擬路徑設(shè)置.png

如上圖,這里要提的就是springboot2.x虛擬路徑的設(shè)置,我這里把圖片上傳保存在了本地電腦的/Users/wudengyao/111111springboot_upload/目錄下,然后具體路徑再根據(jù)用戶的userid建立子文件夾,虛擬路徑設(shè)置完之后就能在本地通過(guò)url直接調(diào)用圖片了


image.png
本地電腦的圖片路徑.png

小程序端代碼:

/**
   * 上傳頭像
   */
  upload(userId,path, sCallback) {
    wx.uploadFile({
      url: config.api_base_url + 'user/upload?userId=' + userId,
      filePath: path,
      name: 'file',
      header: {
        "Content-Type": "application/x-www-form-urlencoded;text/html; charset=utf-8"
      },
      success(res) {
        const data = JSON.parse(res.data);
        console.log(config.api_base_url + data.data.avator);

        sCallback(data);
        
      }
    })

  }

小程序端的代碼,就是請(qǐng)求的時(shí)候傳遞一個(gè)用戶id和文件路徑(由wx.chooseImage返回)

page頁(yè)面代碼:


 uploadAvator(){

    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success:(res)=>{
        const tempFilePaths = res.tempFilePaths

        console.log(tempFilePaths);

        uploadModel.upload(this.data.user.id, tempFilePaths[0], (res) => {
          this.setData({
            avator: config.api_base_url + res.data.avator,
          })
        })
      
      }
    })
  }

wxml代碼


<button bindtap="uploadAvator">上傳頭像</button>
<image src="{{avator}}"></image>

效果圖:

image.png

小程序日志

image.png

java后端日志

image.png

數(shù)據(jù)庫(kù)

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容