<view class="wrap">
<view class="img-box">
<image class="img" src="{{imgUrl}}" mode="aspectFill" bind:longpress="downloadImg"/>
<button class="btn" bind:tap="chooseAndUpload">更新头像</button>
</view>
</view>
data: {
imgUrl: 'https://cdn.pixabay.com/photo/2015/03/03/20/42/man-657869_640.jpg',
tempFilePath: null
},
uploadFileUrl: null
数量count指定1张;默认是9张
mediaType:类型指定是图片image
sourceType:指定从相册活照相机拍摄
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
})
}
})
}
指定上传文件路径filePath:使用图像选择的临时路径
指定name为avatar,便于服务器分辨
指定服务器路由url
upload: function () {
// 如果没有更改照片则提示更改后再上传
if (!this.data.tempFilePath) {
wx.showToast({
title: '请您更改头像之后再进行上传操作',
icon: 'none',
duration: 2000
})
return
}
// 确认更改头像之后再上传
wx.uploadFile({
filePath: this.data.tempFilePath,
name: 'avatar',
// 实际地址视机房服务器环境配置
url: 'http://10.10.151.178:3000/upload',
header:{
'content-type':'multipart/form-data'
},
success: res => {
this.uploadFileUrl = JSON.parse(res.data).url
console.log('上传成功')
wx.showToast({
title: '上传成功',
})
}
})
}
上传成功后,返回的头像图片路径保存在了数据中;利用它下载图片到本地
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]
})
}
})
}
{
fieldname: 'image',
originalname: 'bYmNOVO35pLd787bce43d31211e2a9fb482c28888418.png',
encoding: '7bit',
mimetype: 'image/png',
destination: 'E:\\nodeServer/upload',
filename: 'image1706875478704.png',
path: 'E:\\nodeServer\\upload\\image1706875478704.png',
size: 91117
}