(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)
I want to
Simple way to save multiple files
cshtml
@using (Html.BeginForm("Index","Home",FormMethod.Post,new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Files:</label>
<input type="file" multiple name="files" id="files" /><br><br>
<input type="submit" value="Upload Files" />
<br><br>
@ViewBag.Message
}
Controller
[HttpPost]
public ActionResult Index(HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
}
return View();
}
Giving complete Solution
First use input in .CShtml in MVC View
<input type="file" id="UploadImg" /></br>
<img id="imgPreview" height="200" width="200" />
Now call Ajax call
$("#UploadImg").change(function () {
var data = new FormData();
var files = $("#UploadImg").get(0).files;
if (files.length > 0) {
data.append("MyImages", files[0]);
}
$.ajax({
// url: "Controller/ActionMethod"
url: "/SignUp/UploadFile",
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (response)
{
//code after success
$("#UploadPhoto").val(response);
$("#imgPreview").attr('src', '/Upload/' + response);
},
error: function (er) {
//alert(er);
}
});
});
Controller Json Call
[HttpGet]
public JsonResult UploadFile()
{
string _imgname = string.Empty;
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["MyImages"];
if (pic.ContentLength > 0)
{
var fileName = Path.GetFileName(pic.FileName);
var _ext = Path.GetExtension(pic.FileName);
_imgname = Guid.NewGuid().ToString();
var _comPath = Server.MapPath("/MyFolder") + _imgname + _ext;
_imgname = "img_" + _imgname + _ext;
ViewBag.Msg = _comPath;
var path = _comPath;
tblAssignment assign = new tblAssignment();
assign.Uploaded_Path = "/MyFolder" + _imgname + _ext;
// Saving Image in Original Mode
pic.SaveAs(path);
}
}
return Json(Convert.ToString(_imgname), JsonRequestBehavior.AllowGet);
}
How i do mine is pretty much as above ill show you my code and how to use it with a MYSSQL DB...
Document table in DB -
int Id ( PK ), string Url, string Description, CreatedBy, TenancyId DateUploaded
The above code ID, being the Primary key, URL being the name of the file ( with file type on the end ), file description to ouput on documents view, CreatedBy being who uploaded the file, tenancyId, dateUploaded
inside the view you must define the enctype or it will not work correctly.
@using (Html.BeginForm("Upload", "Document", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="input-group">
<label for="file">Upload a document:</label>
<input type="file" name="file" id="file" />
</div>
}
The above code will give you the browse button, then inside my project I have a class basically called IsValidImage which just checks the filesize is under your specified max size, checks if its an IMG file, this is all in a class bool function. So if true returns true.
public static bool IsValidImage(HttpPostedFileBase file, double maxFileSize, ModelState ms )
{
// make sur the file isnt null.
if( file == null )
return false;
// the param I normally set maxFileSize is 10MB 10 * 1024 * 1024 = 10485760 bytes converted is 10mb
var max = maxFileSize * 1024 * 1024;
// check if the filesize is above our defined MAX size.
if( file.ContentLength > max )
return false;
try
{
// define our allowed image formats
var allowedFormats = new[] { ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif, ImageFormat.Bmp };
// Creates an Image from the specified data stream.
using (var img = Image.FromStream(file.InputStream))
{
// Return true if the image format is allowed
return allowedFormats.Contains(img.RawFormat);
}
}
catch( Exception ex )
{
ms.AddModelError( "", ex.Message );
}
return false;
}
So in the controller:
if (!Code.Picture.IsValidUpload(model.File, 10, true))
{
return View(model);
}
// Set the file name up... Being random guid, and then todays time in ticks. Then add the file extension
// to the end of the file name
var dbPath = Guid.NewGuid().ToString() + DateTime.UtcNow.Ticks + Path.GetExtension(model.File.FileName);
// Combine the two paths together being the location on the server to store it
// then the actual file name and extension.
var path = Path.Combine(Server.MapPath("~/Uploads/Documents/"), dbPath);
// set variable as Parent directory I do this to make sure the path exists if not
// I will create the directory.
var directoryInfo = new FileInfo(path).Directory;
if (directoryInfo != null)
directoryInfo.Create();
// save the document in the combined path.
model.File.SaveAs(path);
// then add the data to the database
_db.Documents.Add(new Document
{
TenancyId = model.SelectedTenancy,
FileUrl = dbPath,
FileDescription = model.Description,
CreatedBy = loggedInAs,
CreatedDate = DateTime.UtcNow,
UpdatedDate = null,
CanTenantView = true
});
_db.SaveChanges();
model.Successfull = true;