小程序 - 头像上传

微信小程序常用API练习 - 头像上传小程序开发笔记

目录

头像上传

准备工作

创建项目

配置导航栏

图片资源

启动服务器

目录结构

头像上传下载页面结构

头像上传下载页面逻辑

头像上传页面样式

功能截图

总结


头像上传

头像上传下载"微信小程序展示了头像信息,并提供了3个按钮,依次为"更改头像"​"头像上传"​"头像下载"​。点击"更改头像"按钮,可以重新选择头像图片;点击"头像上传"按钮,可以将头像上传到服务器;点击"头像下载"按钮,可以从服务器中下载头像图片并预览。

准备工作

在开发前,需要先完成一些准备工作,主要包括创建项目、配置导航栏、复制素材和启动服务器,具体步骤如下:

创建项目

在微信开发者工具中创建一个新的微信小程序项目,项目名称为"头像上传下载",模板选择"不使用模板"。

配置导航栏

在pages/index/index.json文件中配置页面导航栏,具体代码如下:

javascript 复制代码
{
  "usingComponents": {
    "navigation-bar": "/components/navigation-bar/navigation-bar"
  },
  "navigationBarTitleText": "头像上传下载"
}
图片资源

创建images文件夹,并准备一张头像图片。

启动服务器

启动本地HTTP服务器apache和php程序。

服务端具体代码如下:

php 复制代码
<?php

// 创建文件夹
function createPath(string $dirName)
{
    if (!$dirName) return '';

    $dirName = './' . $dirName . '/' . date('Ymd') . '/';
    if (!file_exists($dirName)) {
        mkdir($dirName, 0755, true);
    }

    return $dirName;
}

// 文件路径处理
function replacePath(string $filePath)
{
    if (!$filePath) return '';

    $currentPath = dirname($_SERVER['PHP_SELF']);

    return 'http://127.0.0.1' . $currentPath . ltrim($filePath, '.');
}

$file = $_FILES['image'];
$return = ['state' => 0, 'msg' => 'error', 'file' => null];
if (!empty($file)) {
    $upload_dir = createPath('uploads');
    $filePath = $upload_dir . basename($file['name']);
    if (move_uploaded_file($file['tmp_name'], $filePath)) {
        $return['state'] = 1;
        $return['msg'] = 'success';
        $return['file'] = replacePath($filePath);
    }

}

echo json_encode($return);

在微信开发者工具的本地设置中勾选"不校验合法域名、web-view(业务域名)​、TLS版本以及HTTPS证书"复选框。

目录结构

头像上传下载"微信小程序的目录结构如下图所示:

至此,准备工作已经全部完成。

头像上传下载页面结构

在pages/index/index.wxml文件中编写页面结构,具体代码如下:

XML 复制代码
<!--index.wxml-->
<navigation-bar title="头像上传下载" back="{{false}}" color="black" background="#FFF"></navigation-bar>
<view class="imgbox">
    <image src="{{ imgUrl }}" mode="aspectFit" />
    <button type="primary" size="mini" bindtap="changeImg">更改头像</button>
    <button type="primary" size="mini" bindtap="upload">头像上传</button>
    <button type="primary" size="mini" bindtap="download">头像下载</button>
</view>

头像上传下载页面逻辑

在pages/index/index.js文件的Page({})中编写逻辑代码,具体代码如下:

javascript 复制代码
// index.js
Page({
    data: {
        imgUrl: '/images/guest.jpg', // 头像的初始显示图片
        tempFilePath: null // 用于保存图片文件临时路径
    },
    uploadFileUrl: null, // 保存图片上传之后的图片路径
    // 实现图片选择
    changeImg: function () {
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            success: res => {
                var tempFilePath = res.tempFiles[0].tempFilePath
                this.setData({
                    tempFilePath: tempFilePath,
                    imgUrl: tempFilePath
                })
            }
        })
    },
    // 实现头像的上传
    upload: function () {
        // 如果没有更改照片提示更改后再上传
        if (!this.data.tempFilePath) {
            wx.showToast({
                title: '请您更改头像之后再进行上传操作',
                icon: 'none',
                duration: 2000
            })
            return
        }
        // 确认更改头像之后再上传
        wx.uploadFile({
            filePath: this.data.tempFilePath,
            name: 'image',
            url: 'http://127.0.0.1/mini/upload/service.php',
            success: res => {
                this.uploadFileUrl = JSON.parse(res.data).file
                console.log('上传成功', this.uploadFileUrl)
            }
        })
    },
    // 实现图片下载
    download: function () {
        if (!this.uploadFileUrl) {
            wx.showToast({
                title: '请您上传头像之后再进行下载操作',
                icon: 'none',
                duration: 2000
            })
            return
        }
        wx.showLoading({
            title: '图片下载中,请稍后......',
        })
        wx.downloadFile({
            url: this.uploadFileUrl,
            success: res => {
                wx.hideLoading()
                console.log('下载完成')
                wx.previewImage({
                    urls: [res.tempFilePath]
                })
            }
        })
    }
})

头像上传页面样式

在pages/index/index.wxss文件中对页面样式进行美化。具体代码如下:

css 复制代码
/**index.wxss**/
.imgbox {
    display: flex;
    flex-direction: column;
    text-align: center;
}
.imgbox image {
    margin: 0 auto;
}

.imgbox button {
    margin: 2vh 18vw;
}

功能截图

总结

微信小程序常用API练习 - 头像上传小程序开发笔记

相关推荐
是梦终空30 分钟前
计算机毕业设计267—基于Springboot+vue3+小程序的医院挂号系统(源代码+数据库)
spring boot·小程序·vue·毕业设计·课程设计·医院挂号系统·源代码
kyh10033811202 小时前
微信小游戏《找茬找汉字闯关王》源码赠送
microsoft·微信·微信小程序·微信小游戏·找茬小游戏·微信找茬消除
陈思杰系统思考Jason4 小时前
系统思考:中小企业面临的挑战
百度·微信·微信公众平台·新浪微博·微信开放平台
低代码布道师4 小时前
【教培管家】小程序实战(八)——我的课表
低代码·小程序·云开发
一匹电信狗6 小时前
【Linux我做主】从 fopen 到 open:Linux 文件 I/O 的本质与内核视角
linux·运维·服务器·c++·ubuntu·小程序·开源
2501_915921436 小时前
Fastlane 结合 AppUploader 来实现 CI 集成自动化上架
android·运维·ci/cd·小程序·uni-app·自动化·iphone
2501_915921436 小时前
iOS 抓包怎么绕过 SSL Pinning 证书限制,抓取app上的包
android·网络协议·ios·小程序·uni-app·iphone·ssl
黑睿6 小时前
微信小程序,skyline引擎,display: grid失效问题解决
microsoft·微信小程序·小程序
毕设源码-朱学姐21 小时前
【开题答辩全过程】以 基于微信小程序的大学生安全素质综合培养平台设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
羊群智妍1 天前
2026:GEO监测工具助力AI搜索优化落地
百度·微信·微信公众平台·facebook·新浪微博