前端代码部分:
上传组件主要代码如下:
render() { const { name = "avatar" } = this.props; return ( <Upload name={name} className="avatar-uploader" showUploadList={false} action={`${reqUrl/avatar/saveAvatar?user_id=${user_id}&update_time=${update_time}`} beforeUpload={beforeUpload} onChange={this.handleChange} > </Upload> ); }
reqUrl :请求接口地址,
beforeUpload : 对图片的一些处理,
handleChange :上传成功后对图片的处理,
页面使用
<UploadAvatar name={"cover"} getImageUrl={this.getImageUrl()} />
后端主要代码:
controller下:
const alidata = await ctx.service.avatar.uploadAvatar();
service下:
// 上传头像到阿里云oss async uploadAvatar() { const { ctx } = this; let parts = ctx.multipart({ autoFileds: true }); let stream; const client = new oss({ accessKeyId: "xxx", accessKeySecret: "xxx", bucket: "bucketofreactandeggblog", region: "oss-cn-beijing", }); while ((stream = await parts()) != null) { if (!stream.filename) { break; } let name = new Date() * 1 + path.extname(stream.filename); let res = await client .putStream(`tests/${name}`, stream) .catch(function (err) { console.log("error: %j", err); }); return res; }
以上为上传头像前后端的主要代码,详细代码后面可以去我的github上看,稍后我会添加上我的github地址,如果又发现什么不成熟的地方请多多指教。给我留言即可。