ASP.NET Core文件上傳、下載與刪除


 

首先我們需要創建一個form表單如下:

<form method="post" enctype="multipart/form-data" asp-controller="UpLoadFile" asp-action="FileSave">

        <div>

            <div>

                <p>Form表單多個上傳文件:</p>

                <input type="file" name="files" multiple />

                <input type="submit" value="上傳" />

            </div>

        </div>

    </form>

private IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{

_hostingEnvironment = hostingEnvironment;
}

 

//[RequestSizeLimit(100_000_000)] //最大100m左右
//[DisableRequestSizeLimit] //或者取消大小的限制
public IActionResult Upload()
{
var files = Request.Form.Files;

long size = files.Sum(f => f.Length);

string webRootPath = _hostingEnvironment.WebRootPath;

string contentRootPath = _hostingEnvironment.ContentRootPath;
List<string> filenames=new List<string>();
foreach (var formFile in files)

{

if (formFile.Length > 0)

{
string fileExt = Path.GetExtension(formFile.FileName); //文件擴展名,不含“.”

long fileSize = formFile.Length; //獲得文件大小,以字節為單位

string newFileName = System.Guid.NewGuid().ToString()+ fileExt; //隨機生成新的文件名

var filePath = webRootPath + "/upload/";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
using (var stream = new FileStream(filePath+ newFileName, FileMode.Create))

{
formFile.CopyTo(stream);
}
filenames.Add(newFileName);
}

}

 

return Ok(new { filenames, count = files.Count,size });
}
public IActionResult DownLoad(string file)

{
string webRootPath = _hostingEnvironment.WebRootPath;
var addrUrl = webRootPath+"/upload/"+ file;

var stream = System.IO.File.OpenRead(addrUrl);

string fileExt = Path.GetExtension(file);

//獲取文件的ContentType

var provider = new FileExtensionContentTypeProvider();

var memi = provider.Mappings[fileExt];

return File(stream, memi, Path.GetFileName(addrUrl));

}

public IActionResult DeleteFile(string file)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var addrUrl = webRootPath + "/upload/" + file;
if (System.IO.File.Exists(addrUrl))
{
//刪除文件
System.IO.File.Delete(addrUrl);
}
return Ok(new { file });
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM