@page
@model xxtsoft.Pages.uploadModel
@{
}
<h1>@ViewData["Title"]</h1>
<form method="post" enctype="multipart/form-data" >
<div class="form-group">
<div class="col-md-12">
<input type="file" name="files" multiple />
<input asp-page-handler="Upload" class="btn" type="submit" value="上传" />
</div>
</div>
</form>
@Html.Raw(Model.msgJs)using Furion;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using xxtsoft.Common;
namespace xxtsoft.Pages
{
public class uploadModel : PageModel
{
public string msgJs;//js上传说明
public string foldname;//文传上传目录
public void OnGet()
{
foldname =FunHelper.FilerForm(Request.Query["foldname"]);//过滤非法字符
}
//上传文件是 post 方式,这里加不加都可以
public async Task<IActionResult> OnPostUploadAsync(List<IFormFile> files)
{
long size = files.Sum(f => f.Length); //统计所有文件的大小
var filepath = App.WebHostEnvironment.WebRootPath + "/upLoadfiels/";
foreach (var item in files) //上传选定的文件列表
{
if (item.Length > 0) //文件大小 0 才上传
{
var thispath = Path.Combine(filepath, RandomHelper.GetGuid() + Path.GetExtension(item.FileName)); //当前上传文件应存放的位置item.FileName
if (System.IO.File.Exists(thispath) == true) //如果文件已经存在,跳过此文件的上传
{
//ViewBag.log += "\r\n文件已存在:" + thispath.ToString();
continue;
}
//目录不存在,创建目录
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
//上传文件
using (var stream = new FileStream(thispath, FileMode.Create)) //创建特定名称的文件流
{
try
{
await item.CopyToAsync(stream); //上传文件
}
catch (Exception ex) //上传异常处理
{
throw new Exception(ex.ToString());
}
}
}
}
//msg = "<script>alert('test');</script>";
// Process uploaded files
// Don't rely on or trust the FileName property without validation.
return Page();
}
}
}