Reference:
using System.Net.Http.Headers;
Dependency Injection:
private readonly IHostingEnvironment hostingEnvironment;public HomeController(IHostingEnvironment env){ this.hostingEnvironment = env;}
cshtml Use the h-ui Admin template ( if you don't need to go directly to the file tag):
Remove the accept restriction from the file tag to pass various files
<form asp-controller= "Home" role= "form" asp-action= "Importexcel" enctype= "Multipart/form-data" method= "POST" class= "Form Form-horizontal" id= "Form-add" > <div class= "row cl" > <label C lass= "Form-label col-xs-4 col-sm-3" ><span class= "c-red" >*</span> Select Excel <span style= "color:red;" >xlsx</span> Import:</label> <div class= "formcontrols col-xs-8 col-sm-9" > @*//with text box *@ <span class= "Btn-upload form-group" > <input class= "input- Text Upload-url radius "type=" text "name=" UploadFile "id=" UploadFile "readonly> <a href=" Java Script:void (); "class=" btn btn-primary radius "> Browse files </a> <input type= "file" multiple name= "Fileinput" class= "Input-file" accept= ". xlsx"/> </span></div> </div> <div class= "row cl" > <div class= "col-xs-8 col-sm-9 Col-xs-offset-4 col-sm-offset-3 "> <input class=" btn btn-primary radius "type=" submit "value=" &am p;nbsp; Submit " > </div> </div> </form>
Action:
[HttpPost] public async task<iactionresult> Importexcel (iformfile fileinput) {try { var filename = contentdispositionheadervalue.parse (fileinput. contentdisposition). FileName; The original file name (including the path) var extname = filename. Substring (filename. LastIndexOf ('. ')). Replace ("\" "," ");//Extension string ShortFileName = $" {Guid.NewGuid ()}{extname} ";//new file name string Filesavepath = Hostingenvironment.webrootpath + @ "\upload\";//File temp directory, delete filename = Filesavepath + Sho after import is complete Rtfilename; The new file name (including the path) if (! Directory.Exists (Filesavepath)) {directory.createdirectory (Filesavepath); } using (FileStream fs = System.IO.File.Create (filename))//Create new file {F Ileinput. CopyTo (fs);//Copy file FS. Flush ();//clear buffer data//The file can be used for business operations according to filename "File server disk Path"} After processing is complete, delete the uploaded file if (System.IO.File.Exists (filename)) {System.IO.Fi Le. Delete (filename); } return new Jsonresult (ImportResult); } catch (Exception ex) {}}
. NET core uploads Excel files