上传视频,图片等都是调用wx.uploadFile,后台接口都不用改。
.wxml
<button bindtap="chooseVideo">
添加视频</button>
<block wx:if="{{src != ''}}">
<video src="{{src}}"></video>
</block>
.js
Page({
data: {
src: ''
},
//选择视频
chooseVideo: function() {
var that = this
wx.chooseVideo({
success: function(res) {
that.setData({
src: res.tempFilePath,
})
that.uploadvideo();
}
})
},
uploadvideo: function() {
var src = this.data.src;
wx.uploadFile({
url: '**************/Upload', //服务器接口
filePath: src,
header: {
'content-type': 'multipart/form-data'
},
name: 'files',
success: function(res) {
console.log(res.data)
},
fail: function() {
console.log('接口调用失败')
}
})
}
})
后台接口
[WebMethod(EnableSession = true)]
public void Upload()
{
//获取文件路径
HttpFileCollection files = HttpContext.Current.Request.Files;
//返回的对象初始化
object obj = null;
//获取项目路径
string sPath = System.Web.HttpContext.Current.Request.PhysicalPath;
//得到上一级路径
DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}..\..\", sPath));
string sFilePath = Path.Combine(di.FullName, "Upload", DateTime.Today.Year.ToString(), DateTime.Today.Month.ToString(), DateTime.Today.Day.ToString(), "");
//不存在路径则创建该路径
if (!Directory.Exists(sFilePath))
{
Directory.CreateDirectory(sFilePath);
}
foreach (string key in files.AllKeys)
{
HttpPostedFile file = files[key];//file.ContentLength文件长度
if (string.IsNullOrEmpty(file.FileName) == false)
{
string fileName = Path.GetFileName(file.FileName);// 原始文件名称
string fileExtension = Path.GetExtension(fileName); // 文件扩展名
string saveName = Guid.NewGuid().ToString() + fileExtension; // 保存文件名称
string fileSaveAsName = string.Format(@"{0}\{1}", sFilePath, saveName);//保存文件路径
file.SaveAs(fileSaveAsName);//保存
string sUrl = Path.Combine("Upload", DateTime.Today.Year.ToString(), DateTime.Today.Month.ToString(), DateTime.Today.Day.ToString(), saveName);//Url地址
obj = (new { resultCode = "001", FileName = saveName, Url ="http://localhost:14146/"+sUrl });
}
else obj = (new { resultCode = "003", Message = "请选择要上传的文件!" });
}
HttpContext.Current.Response.Write(obj);
}
结果及返回数据