最近在研究微信开发,做了一个平台,但是上传素材至微信服务器频频出现问题,各种尝试后,最终解决了,特此记录下。
话不多说上代码:
前端代码
前端采用 element-ui/el-upload
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <el-upload action="/dev-api/upload" :file-list="form.thumb" name="media" list-type="picture-card" :auto-upload="true" :headers="headerObj" :on-change="handleChange" > <i slot="default" class="el-icon-plus" /> <div slot="file" slot-scope="{ file }" class="thumb-img" :style="'background-image: url(' + file.url + ')'" > <span class="el-upload-list__item-actions"> <span class="el-upload-list__item-delete" @click="handleRemove(file)" > <i class="el-icon-delete" /> </span> </span> </div> </el-upload>
|
效果:
后台代码
后端采用egg.js
1 2 3 4 5 6 7 8 9 10
| multipart: { mode: 'file', fileExtensions: [ '.jpg', '.jpeg', '.png' ], }, security: { csrf: { ignore: ctx => isInnerIp(ctx.ip), }, },
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
const formstream = require('formstream');
const access_token = await service.weixin.token(settingOne);
const file = ctx.request.files[0]; const imgbase64 = await fs.readFileSync(file.filepath, 'base64'); const dataBuffer = Buffer.from(imgbase64, 'base64');
const form = formstream(); form.buffer('media', dataBuffer, file.filename, file.mime);
const { data: result } = await ctx.curl(`https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${access_token}&type=image`, { method: 'post', headers: form.headers(), stream: form, dataType: 'json', });
if (result.errcode) return ctx.helper.error(ctx, 500, result); ctx.helper.success(ctx, null, '上传成功');
|
大功告成!撒花💖