微信小程序简单实现上传的功能,这里以上传图片为例:
页面如下:
<button bindtap="upload" type="primary">点击上传</button>
<image src="{{imgurl}}" mode="aspectFill" />
添加一个按钮点击触发上传事件,并且添加一个图片
对应js如下:
Page({
data: {
imgurl:'', // 图片路径
},
upload:function(){
let that = this
wx.chooseImage({
success (res) {
wx.showLoading({
title: '上传中,请稍等...',
})
let tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'http://localhost:52843/FileUpload', //上传文件的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'admin'
},
success (res){
wx.hideLoading();
let data =JSON.parse(res.data)
that.setData({
imgurl: 'http://localhost:52843' + data.data
})
//do something
},
fail: function(res) {
wx.hideLoading()
wx.showToast({
title: '上传失败,请重新上传',
icon: 'none',
duration: 2000
})
}
})
}
})
},
})
该接口后台使用.net来实现,具体代码如下:
public class FileUploadController : Controller
{
public JsonResult Index()
{
LogHelper.Default.WriteInfo("进入后台");
var files = HttpContext.Request.Files;
var sucess = false;
var imgurl = "";
if (files.Count > 0)
{
files[0].SaveAs(Server.MapPath("~/doc/" + System.IO.Path.GetFileName(files[0].FileName)));
sucess = true;
imgurl = "/doc/" + System.IO.Path.GetFileName(files[0].FileName);
}
var obj = new
{
data = imgurl
success = sucess
};
return new JsonResult() { Data = obj, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}