This example for everyone to share the single file upload, multi-file upload function for your reference, the specific content as follows
Single File Upload
Uploading files is a common feature in Web applications. It is easy to upload files and save them on the server in ASP. Here's a demonstration of how to upload a file in an ASP. NET Core project.
First, create an ASP. NET Core project, then add a HomeController to the controller file and add a new.cshtml view file to the Home folder of the Views folder. Such as:
Add a UserViewModel.cs in the Model folder with the following code:
public class userviewmodel{ [Required] [Display (name = ' name ')] public string name {get; set;} [Required] [Display (Name = "id")] [RegularExpression (@ "^ (\d{15}$|^\d{18}$|^\d{17} (\d| X|X)) $ ", errormessage =" ID number not valid ")] public string Idnum {get; set;} public string Idcardimgname {get; set;} [Required] [Display (Name = "id card attachment")] [Fileextensions (Extensions = ". Jpg,.png", errormessage = "Picture format error")] Public Iformfile idcardimg {get; set;}}
Then add a new.cshtml view file in the Views folder:
@model userviewmodel <form asp-controller= "Home" role= "form" asp-action= "New" enctype= "Multipart/form-data" method = "POST" > <div class= "Form-group" > <label asp-for= "Name" ></label> <input type= "Text" class= "Form-control" asp-for= "Name"/> </div> <div class= "Form-group" > <label Asp-for= "Idnum" ></label> <input type= "text" class= "Form-control" asp-for= "Idnum"/> </ div> <div class= "Form-group" > <label asp-for= "idcardimg" ></label> <input Type= "File" asp-for= "idcardimg"/> <p class= "Help-block" > Upload. </p> </div> <button type= "Submit" class= "BTN Btn-default" > Submit </button></form >
In HomeController, add the corresponding Action method for the page:
[Httppost]public iactionresult New ([fromservices]ihostingenvironment env, [Fromservices]appdbcontext DbContext, Userviewmodel user) { var fileName = path.combine ("Upload", DateTime.Now.ToString ("MMDDHHMMSS") + ". jpg"); using (var stream = new FileStream (path.combine) (env. Webrootpath, FileName), filemode.createnew) { user. Idcardimg.copyto (stream); } var users = dbcontext.set<user> (); var dbUser = new User () { Name = User. Name, idcardnum = user. Idnum, idcardimgname = FileName }; Users. ADD (dbUser); Dbcontext.savechanges (); Return Redirecttoaction (nameof (Index));}
Multiple file uploads
Multiple file uploads and single file uploads are similar, the form's ViewModel uses icollection<ifromfile>, and then the form <input type= "file" asp-for= "idcardimg" mulpitle/ > Add Mulpitle on it (only support H5).
Sample source Code
Note: The sample data store uses the Sqlite, Code first method to generate the database.