日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET Core文件上传、下载与删除

發(fā)布時間:2023/11/30 asp.net 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Core文件上传、下载与删除 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

?

首先我們需要創(chuàng)建一個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; //獲得文件大小,以字節(jié)為單位

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 });
}

轉(zhuǎn)載于:https://www.cnblogs.com/cb521413/p/9366156.html

總結(jié)

以上是生活随笔為你收集整理的ASP.NET Core文件上传、下载与删除的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。