一、小程序图片上传示例2
选择图片,先预览,点击提交时上传
1.wxml
<button type='primary' plain='true' bindtap='getImg'>
选择图片
</button>
<image src='{{imgpath}}'></image>
<button type='warn' plain='true' bindtap='uploadImg'>
确定上传
</button>
2.js 处理
/**
* 页面的初始数据
*/
data: {
imgpath: '',
},
getImg: function () {
var _this = this;
//选择图片
wx.chooseImage({
success: function (res) {
//预览显示
_this.setData({
imgpath: res.tempFilePaths[0]
});
},
})
},
uploadImg: function () {
var _this = this;
console.info(_this.data);
//上传处理
wx.uploadFile({
url: 'http://localhost:63588/ashx/upload_form.ashx', //上传地址
filePath: _this.data.imgpath,//上传图片路径
name:'file',
success: res => {
console.info(res);
}
})
},
二、上传示例3,前台图片压缩处理后,再上传
1.wxml
<button bindtap='getImg'>
选择图片,压缩后上传
</button>
<canvas canvas-id='canvas1' style='width:{{imgwidth}}px;height:{{imgheight}}px;'>
</canvas>
2.重点js 处理
//选择图片
getImg: function () {
var _this = this;
var ctx = wx.createCanvasContext('canvas1', this);
//选择图片
wx.chooseImage({
success: function (res) {
//图片预览压缩处理 ---指定图片最大宽度缩放
var imgPath = res.tempFilePaths[0];
var maxWidth = 100;
wx.getImageInfo({
src: imgPath,
success: res => {
_this.setData({
imgwidth: res.width,
imgheight: res.height
});
//绘制处理 (比例不变,最大宽度高度为100)
var width = 100, height = 100;
if (res.width > res.height) {
width = maxWidth;
height = res.height / res.width * maxWidth;
} else {
height = maxWidth;
width = res.width / res.height * maxWidth;
}
ctx.drawImage(imgPath, 0, 0, res.width, res.height);
ctx.draw(true, function () {
//导出图片为临时文件,然后上传
wx.canvasToTempFilePath({
canvasId: 'canvas1',
fileType: 'jpg',
destWidth: width,
destHeight: height,
success: res => {
console.info(res.tempFilePath);
//上传
wx.uploadFile({
url: 'http://localhost:63588/ashx/upload_form.ashx',
filePath: res.tempFilePath,
name: 'file',
success: res => {
wx.showModal({
title: '提示',
content: '上传成功',
})
}
})
}
}, this);
});
}
})
},
})
},
更多: