頭像修改功能

準(zhǔn)備

后端接口

  • 添加pom.xml依賴
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.8.3</version>
</dependency>
  • 測(cè)試阿里云OSS上傳功能 AliOSSTest
public class AliOSSTest {
    public static void main(String[] args) {
        // Endpoint以杭州為例极颓,其它Region請(qǐng)按實(shí)際情況填寫朱盐。
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云主賬號(hào)AccessKey擁有所有API的訪問(wèn)權(quán)限,風(fēng)險(xiǎn)很高
        String accessKeyId = "****";
        String accessKeySecret = "****";
        String bucketName = "****";
        String filedir = "avatar/";
        String fileKey = "hello.jpg";
        // 創(chuàng)建OSSClient實(shí)例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上傳文件
        PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileKey, new File("D:\\bg.jpg"));
        //時(shí)間戳
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, filedir + fileKey, expiration);
        System.out.println(url);
        ossClient.shutdown();
    }
}
  • 編寫上傳接口程序菠隆,然后用swagger測(cè)試
package com.soft1721.jianyue.api.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.soft1721.jianyue.api.util.ResponseResult;
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 java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping(value = "/api")
public class UploadController {
    @PostMapping("/avatar/upload")
    public String ossUpload(@RequestParam("file") MultipartFile sourceFile) {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "***";
        String accessKeySecret = "***";
        String bucketName = "***";
        String filedir = "avatar/";
        // 獲取源文件名
        String fileName = sourceFile.getOriginalFilename();
        // 獲取源文件名后綴
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //uuid生成主文件名
        String prefix = UUID.randomUUID().toString();
        //新文件名
        String newFileName = prefix + suffix;
        //File類型的臨時(shí)文件
        File tempFile = null;
        try {
            //創(chuàng)建臨時(shí)文件兵琳,用uuid主文件名+原后綴名
            tempFile = File.createTempFile(prefix, prefix);
            // MultipartFile轉(zhuǎn)成File
            sourceFile.transferTo(tempFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, filedir + newFileName, tempFile);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, filedir + newFileName, expiration);
        ossClient.shutdown();
        //URL返回給客戶端
        return url.toString();
    }
}
  • 編寫修改個(gè)人頭像的接口,并且用JUnit浸赫、swagger測(cè)試
    省略mapper層闰围、service層,自行完成并進(jìn)行單元測(cè)試
    UserController類的修改用戶頭像接口
@PostMapping("/avatar")
public String ossUpload(@RequestParam("file") MultipartFile sourceFile,@RequestParam("userId") int userId) {
    String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    String accessKeyId = "***";
    String accessKeySecret = "***";
    String bucketName = "***";
    String filedir = "avatar/";
    // 獲取文件名
    String fileName = sourceFile.getOriginalFilename();
    // 獲取文件后綴
    String suffix = fileName.substring(fileName.lastIndexOf("."));
    //uuid生成主文件名
    String prefix = UUID.randomUUID().toString();
    String newFileName = prefix + suffix;
    File tempFile = null;
    try {
        //創(chuàng)建臨時(shí)文件
        tempFile = File.createTempFile(prefix, prefix);
        // MultipartFile to File
        sourceFile.transferTo(tempFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    ossClient.putObject(bucketName, filedir + newFileName, tempFile);
    Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
    // 生成URL
    URL url = ossClient.generatePresignedUrl(bucketName, filedir + newFileName, expiration);
    ossClient.shutdown();
    //根據(jù)userId查詢出原始用戶數(shù)據(jù)
    User user = userService.getUserById(userId);
    //更新頭像屬性
    user.setAvatar(url.toString());
    //修改用戶信息并持久化
    userService.updateUser(user);
    //將頭像鏈接返回給客戶端既峡,以便實(shí)時(shí)預(yù)覽
    return url.toString();
}

前端

  • setting頁(yè)面點(diǎn)擊用戶資料跳轉(zhuǎn)到user_info頁(yè)面,pages.json中注冊(cè)新頁(yè)面
<navigator url="../user_info/user_info">
    個(gè)人資料
</navigator>
  • user_info頁(yè)面
<template>
    <view class="container">
        <view class="list">
            <view class="list-item list-item-heigher">
                <view class="left">昵稱</view>
                <view class="right">{{nickname}}</view>
                <navigator url=""></navigator>
            </view>
            <view class="list-item list-item-heigher">
                <view class="left">頭像</view>
                <view class="right"><image :src="avatar" class="avatar" @tap="showActionSheet"></image></view>
            </view>
            <view class="list-item list-item-heigher"><view class="left">修改密碼</view></view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            nickname: '',
            avatar:'',
            userId: uni.getStorageSync('login_key').userId
        };
    },
    onLoad() {
    },
    onShow() {
        var _this = this;
        uni.request({
            url: 'http://localhost:8080/api/user/' + uni.getStorageSync('login_key').userId,
            method: 'GET',
            header: { 'content-type': 'application/json' },
            success: res => {
                if (res.data.code === 0) {
                    console.log(res.data.data.avatar+'————————————');
                    _this.avatar = res.data.data.avatar;
                    _this.nickname = res.data.data.nickname;
                }
            }
        });
    },
    methods: {
        showActionSheet: function() {
            console.log('show');
            var _this = this;
            uni.showActionSheet({
                itemList: ['拍照', '從相冊(cè)選擇'],
                success: function(res) {
                    console.log('選中了第' + (res.tapIndex + 1) + '個(gè)按鈕');
                    //選擇的是拍照功能
                    if (res.tapIndex == 0) {
                        uni.chooseImage({
                            count: 1,
                            sourceType: ['camera'],
                            success: function(res) {
                                uni.saveImageToPhotosAlbum({
                                    filePath: res.tempFilePaths[0],
                                    success: function() {
                                        console.log('save success');
                                        uni.uploadFile({
                                            url: 'http://localhost:8080/api/user/avatar', //僅為示例碧查,非真實(shí)的接口地址
                                            filePath: res.tempFilePaths[0],
                                            name: 'file',
                                            formData: {
                                                userId: _this.userId
                                            },
                                            success: uploadFileRes => {
                                                console.log(uploadFileRes.data);
                                                _this.avatar = uploadFileRes.data;
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                    //從相冊(cè)選擇
                    if (res.tapIndex == 1) {
                        uni.chooseImage({
                            count: 1, //默認(rèn)9
                            sizeType: ['original', 'compressed'], //可以指定是原圖還是壓縮圖运敢,默認(rèn)二者都
                            sourceType: ['album'], //從相冊(cè)選擇
                            success: function(res) {
                                console.log(JSON.stringify(res.tempFilePaths));
                                uni.uploadFile({
                                    url: 'http://localhost:8080/api/user/avatar', 
                                    filePath: res.tempFilePaths[0],
                                    name: 'file',
                                    formData: {
                                        userId: _this.userId
                                    },
                                    success: uploadFileRes => {
                                        console.log(uploadFileRes.data);
                                        _this.avatar = uploadFileRes.data;
                                    }
                                });
                            }
                        });
                    }
                },
                fail: function(res) {
                    console.log(res.errMsg);
                }
            });
        }
    }
};
</script>

<style>
.list-item-heigher {
    height: 80px;
    display: flex;
}
.left {
    flex: 1 1 30%;
}
.right {
    flex: 1 1 70%;
}
</style>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市忠售,隨后出現(xiàn)的幾起案子传惠,更是在濱河造成了極大的恐慌,老刑警劉巖稻扬,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件卦方,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡泰佳,警方通過(guò)查閱死者的電腦和手機(jī)盼砍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)逝她,“玉大人浇坐,你說(shuō)我怎么就攤上這事∏穑” “怎么了近刘?”我有些...
    開(kāi)封第一講書人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我觉渴,道長(zhǎng)介劫,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任案淋,我火速辦了婚禮蜕猫,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘哎迄。我一直安慰自己回右,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布漱挚。 她就那樣靜靜地躺著翔烁,像睡著了一般。 火紅的嫁衣襯著肌膚如雪旨涝。 梳的紋絲不亂的頭發(fā)上蹬屹,一...
    開(kāi)封第一講書人閱讀 51,541評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音白华,去河邊找鬼慨默。 笑死,一個(gè)胖子當(dāng)著我的面吹牛弧腥,可吹牛的內(nèi)容都是我干的厦取。 我是一名探鬼主播,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼管搪,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼虾攻!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起更鲁,我...
    開(kāi)封第一講書人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤霎箍,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后澡为,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體漂坏,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年媒至,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了顶别。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡塘慕,死狀恐怖筋夏,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情图呢,我是刑警寧澤条篷,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布骗随,位于F島的核電站,受9級(jí)特大地震影響赴叹,放射性物質(zhì)發(fā)生泄漏鸿染。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一乞巧、第九天 我趴在偏房一處隱蔽的房頂上張望涨椒。 院中可真熱鬧,春花似錦绽媒、人聲如沸蚕冬。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)囤热。三九已至,卻和暖如春获三,著一層夾襖步出監(jiān)牢的瞬間旁蔼,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工疙教, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留棺聊,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓贞谓,卻偏偏與公主長(zhǎng)得像限佩,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子经宏,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355