微信小程序上传文件

时间:2021-03-28 16:45:19

wx.chooseImage({ count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths
console.log(tempFilePaths[0])
wx.uploadFile({
url: 'https://gh.ydfos.com/wxfileUplad/Post', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData:{
'address': 'jinhua',
'name':'zjh'
},
success: function(res2){
console.log(res2);
var data = res2.data
console.log(data);
//do something
}
})
}
}
)


服务端代码
var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "config/log4net.config");
XmlConfigurator.ConfigureAndWatch(logCfg);
var logger = LogManager.GetLogger("log");

try
{

logger.Info("files:" + Request.Files.Count);
logger.Info("filename:" + Request.Files[0].FileName);


string filepath = Server.MapPath("/upload/");
Stream sin = Request.InputStream;

string name = Request.QueryString["name"];
string fileExt = Path.GetExtension(Request.Files[0].FileName).ToLower();
string fileName = Guid.NewGuid().ToString() + fileExt;
Request.Files[0].SaveAs(filepath + fileName);



logger.Info("name:" + Request.Form["name"] + ";address:" + Request.Form["address"]);

return Json(new { success="ok"}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
logger.Error(ex.Message);
return Json(new { success = "fail" }, JsonRequestBehavior.AllowGet);
}