页面代码
<van-cell-group>
<van-uploader v-model="fileList"
:after-read="afterRead"
multiple
:before-delete="remove"
:max-count="3" />
</van-cell-group>
方法
afterRead(file) {
let content = file.file;
let formData = new FormData();
formData.append("upload", content);
axios({
method: "post",
//服务器上传地址
url: '/FMFamily/UplaodImg',
data: formData,
headers: {
// 修改请求头
"Content-Type": "multipart/form-data"
}
}).then(res => {
if (res.data.Status) {
this.imgList.push({ url: res.data.Data, lastModified: content.lastModified });
}
});
}
remove(file) {
for (var i = 0; i < this.imgList.length; i++) {
if (this.imgList[i].lastModified == file.file.lastModified) {
this.imgList.splice(i, 1);
this.fileList.splice(i, 1);
}
}
},
后台代码
public ActionResult UplaodImg()
{
if (Request.Files.Count > 0)
{
//名称
string name = DateTime.Now.ToString("yyyyMMdd");
//虚拟目录 实际地址
string pathUrl = Server.MapPath($"~/UploadImg/{name}").ToString();
// 创建目录c:\name
if (!Directory.Exists(pathUrl))
{
Directory.CreateDirectory(pathUrl);
}
var file = Request.Files["upload"];
string fileName = file.FileName.Split('.')[0];
string extension = file.FileName.Split('.')[1];
string savePath = Server.MapPath($"~/UploadImg/{name}/{fileName}{ConvertHelper.ToString(DateTime.Now, "yyyyMMddHHmmss")}.{extension}");
string filePath = $"/UploadImg/{name}/{fileName}{ConvertHelper.ToString(DateTime.Now, "yyyyMMddHHmmss")}.{extension}";
file.SaveAs(savePath);
return Json(new { Status = true, Data = filePath });
}
return Json(new { Status = false });
}