前端(.wxml)

<view id="view1">
<view id="btns">
<image id="ima1" mode="aspectFitf" src="{{src}}"></image>
<button type="primary" bindtap="btntakephoto">拍摄照片</button>
<button type="primary" bindtap="btnchoosephoto">选择照片</button>
<button type="primary" bindtap="btnupload">上传</button>
</view>
</view>

样式(wxss)

button{
margin: 8rpx;
padding: 0rpx;
font-size: 30rpx;
width: 200rpx;
float: left;
}
#view1
{
width: %;
height: %;
}
#btns
{
margin: 50rpx;
padding: 0rpx;
}
image{
width: 650rpx;
height: 1050rpx;
background-color: lavender;
}

js(.js)

Page({
data: {
filepath:"",
},
onLoad: function (options) {
this.ctx = wx.createCameraContext()
},
//拍摄照片
btntakephoto: function () {
this.ctx.takePhoto({
quality: 'high',
success: (res) => {
this.setData({
src: res.tempImagePath,
filepath: res.tempImagePath[],
})
}
})
},
//选择照片
btnchoosephoto: function() {
wx.chooseImage({
count: , // 默认9
sizeType: ['original'],
sourceType: ['camera'],
success:(res) => {
this.setData({
src: res.tempFilePaths[],
filepath: res.tempFilePaths[],
});
}
})
},
//上传图片
btnupload: function () {
if (this.data.filepath == "")
{
wx.showToast({
title: '没有选择图片',
icon: 'none',
duration:
})
}
else
{
wx.uploadFile({
url: 'http://localhost:9965/api/image/WxPostFile',
filePath: this.data.filepath,
name: 'file',
formData: {
filename: ''
},
success(res) {
console.log(res);
wx.showToast({
title: "上传成功",
icon: 'success',
duration:
})
}
})
}
}
})

json配置(.json)

{
"navigationBarTitleText": "上传图片",
"navigationBarBackgroundColor": "#003a9b",
"navigationBarTextStyle": "white"
}

后台c#

 #region 测试微信小程序图片上传
[HttpPost]
public HttpResponseMessage WxPostFile()
{
bool isSuccess = false;
try
{
HttpPostedFile file = HttpContext.Current.Request.Files[];
var filename = HttpContext.Current.Request["filename"];
string path = AppDomain.CurrentDomain.BaseDirectory + "Out";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
//var mapPath = HttpContext.Current.Server.MapPath(path); //硬盘物理目录
var fileExt = Path.GetExtension(file.FileName);//文件后缀名(.png)
var mapPathFullPath = path + "\\" + filename + fileExt; //硬盘物理路径
file.SaveAs(mapPathFullPath);
isSuccess = true;
}
catch (Exception ex)
{
isSuccess = false;
}
var resultObj = JsonConvert.SerializeObject(isSuccess);
HttpResponseMessage result = new HttpResponseMessage
{
Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json")
};
return result;
}
#endregion

本地测试

微信小程序上传图片及本地测试-LMLPHP

微信小程序上传图片及本地测试-LMLPHP

05-11 22:23