html示例:
<div class="custom-file">
<label class="custom-file-label" for="customFileHeardPhoto">HeardPhoto</label>
<input type="file" class="custom-file-input" @@change="onchangemd" id="customFileHeardPhoto">
</div>
js代码
function onchangemd(e) {
//存储file信息
console.log(e.target.files)//这个就是选中文件信息
var formData = new FormData();
formData.append("file", e.target.files[0]);//可以上传一个图片或者添加多个
多个示例代码:
let formdata = new
FormData()
Array.from(e.target.files).map(item => {
console.log(item)
formdata.append(
"file"
, item)
//将每一个文件图片都加进formdata
})
// 发送请求
$.ajax({
url: "@Url.Content("/online/ImgUpload")",
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (msg) {
if (msg.suc) {
this.User.HeardPhoto = msg.msg
}
},
error: function (msg) {
}
});
}
后台代码:
public ActionResult ImgUpload()
{
//上传图片可以生成一个独有的路径
try
{
HttpPostedFileBase postFile = Request.Files["file"];
if (postFile != null)
{
string fileExt = postFile.FileName.Substring(postFile.FileName.LastIndexOf("."));
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExt;
string upLoadPath = "~/Content/image/";//上传目录的相对路径
string fullUploadPath = Server.MapPath(upLoadPath);//把路径转换为物理路径
postFile.SaveAs(fullUploadPath + newFileName);//核心方法 保存到文件夹中
return Json(new ResData<string>(true, "/Content/image/" + newFileName));
}
else
{
return Json(new ResData<string>(false, "添加失败"));
}
}
catch (Exception ex)
{
return Json(new ResData<string>(false, "添加失败" + ex.Message));
}
}