uniapp中微信小程序取微信头像并上传到.net core后端

发布时间 2023-08-09 09:19:22作者: 牛腩
uniapp中微信小程序取微信头像并上传到.net core后端
2023年08月09日 后端net7测试成功,先记下来,以后要用的时候直接来这复制粘贴
前端uniapp里的vue代码:
 
<template>
    <view>
         
        <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            取微信头像
        </button>
        <view>头像:{{face}}</view>
        <image :src="face" mode="aspectFit"></image>
 
    </view>
</template>

<script>
    export default {
        data() {
            return { 
                face: '', 
            }
        },
        methods: { 
            onChooseAvatar(e) {
                this.face = e.detail.avatarUrl;
                console.log("头像:" + this.face);
                var uploadurl =  "http://localhost:5049/wx/imgupload"
                uni.uploadFile({
                    url: uploadurl,
                    filePath: this.face,
                    name: 'file',
                    formData: {
                        'openid': '123456'
                    },
                    success: (uploadFileRes) => {
                        console.log(uploadFileRes.data);
                        if(uploadFileRes.data.code==0){
                            var fronturl = uploadFileRes.data.data.fronturl;
                            var src = uploadFileRes.data.data.src;
                            this.face = fronturl+src;
                        }
                    }
                });
            }
             
        }
    }
</script>

<style>
    button,
    input {
        border: 1px solid darkgray;

    }
</style>

  

后端NET7代码,用了WEB API:
using JCT.DAL;
using JCT.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar.Extensions;

namespace JCT.Web.ApiController
{
    [Route("api/[controller]")]
    [ApiController]
    public class WXController : ControllerBase
    {
        //用于读取网站静态文件目录
        private Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv;

        public WXController(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv)
        {
            this.hostingEnv = hostingEnv;
        }


        [HttpPost("ImgUpload")]
        public IActionResult ImgUpload([FromForm] string openid)
        {
            if (Request.Form.Files.Count == 0)
            {
                return new JsonResult(new { code = 1, msg = "文件为空。" });
            }
            var imgFile = Request.Form.Files[0];
            if (imgFile != null && !string.IsNullOrEmpty(imgFile.FileName))
            {
                long size = 0;
                string tempname = "";
                var filename = System.Net.Http.Headers.ContentDispositionHeaderValue
                                .Parse(imgFile.ContentDisposition)
                                .FileName
                                .Trim();
                var extname = filename.Substring(filename.LastIndexOf('.'), filename.Length - filename.LastIndexOf('.')); //扩展名,如.jpg

                extname = extname.Replace("\"", "");

                #region 判断后缀
                if (!extname.ToLower().Contains("jpg") && !extname.ToLower().Contains("png") && !extname.ToLower().Contains("gif")
                    && !extname.ToLower().Contains("jpeg"))
                {
                    return new JsonResult(new { code = 1, msg = "只允许上传jpg,png,gif格式的图片.", });
                }
                #endregion

                #region 判断大小
                long mb = imgFile.Length / 1024 / 1024; // MB
                if (mb > 5)
                {
                    return new JsonResult(new { code = 1, msg = "只允许上传小于 5MB 的图片.", });
                }
                #endregion

                var filename1 = System.Guid.NewGuid().ToString().Substring(0, 6) + extname;
                tempname = filename1;
                var path = hostingEnv.WebRootPath; //网站静态文件目录  wwwroot
                string dir = DateTime.Now.ToString("yyyyMMdd");
                //完整物理路径
                string wuli_path = path + $"{Path.DirectorySeparatorChar}upload{Path.DirectorySeparatorChar}{dir}{Path.DirectorySeparatorChar}";
                if (!System.IO.Directory.Exists(wuli_path))
                {
                    System.IO.Directory.CreateDirectory(wuli_path);
                }
                filename = wuli_path + filename1;
                size += imgFile.Length;
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    imgFile.CopyTo(fs);
                    fs.Flush();
                }
                string fronturl = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Host + ":" + HttpContext.Request.Host.Port;
                return new JsonResult(new
                {
                    code = 0,
                    msg = "上传成功",
                    data = new
                    {
                        fronturl = fronturl,
                        src = $"/upload/{dir}/{filename1}",
                        title = filename1
                    }
                });
            }
            return new JsonResult(new { code = 1, msg = "上传失败", });
        }


    }
}