First we need to create a form form as follows:
<form method= "POST" enctype= "Multipart/form-data" asp-controller= "UploadFile" asp-action= "FileSave" >
<div>
<div>
<p>form form multiple upload files:</p>
<input type= "file" name= "files" multiple/>
<input type= "Submit" value= "Upload"/>
</div>
</div>
</form>
Private Ihostingenvironment _hostingenvironment;
Public HomeController (Ihostingenvironment hostingenvironment)
{
_hostingenvironment = hostingenvironment;
}
[Requestsizelimit (100_000_000)]//maximum 100m or so
[Disablerequestsizelimit]//or cancellation of size limits
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); File extension, not including "."
Long fileSize = formfile.length; Gets the file size, in bytes
String newfilename = System.Guid.NewGuid (). ToString () + Fileext; Randomly generate a new file name
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);
Get the contenttype of a file
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))
{
deleting files
System.IO.File.Delete (Addrurl);
}
Return Ok (new {file});
}
ASP. NET core file upload, download and delete