ienumerable , looping in mvc - c#

I'm creating a page with multiple file uploader in MVC.
What I want to achieve is when I submit values the images uploaded should be named as guid and an incrementing i value, like guid0 , guid1, guid2. I tried for loop but its saving only one image until loop ends . i++ isn't working though.
My controller looks like this:
public ActionResult Home(SomeClass someclass, IEnumerable<HttpPostedFileBase> files)
{
var guid = Guid.NewGuid().ToString();
someclass.filename = guid;
int i = 0;
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = guid + "" + i + ".jpg";
var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
file.SaveAs(path);
i++;
}
}
db.someclasses.Add(someclass);
db.SaveChanges();
return RedirectToAction("Preview");
}
And my view looks like this
<input type="file" name="files" id=1>
<input type="file" name="files" id=2>
Update : I'm receiving 11 files at the if loop but once they go through the loop there is only single image in the images folder named fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0 . what i'm trying to achieve is all 11 images named as fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0, fdea36c3-545a-4e08-8af4-7fa6bd88bc6b1,fdea36c3-545a-4e08-8af4-7fa6bd88bc6b2.....so on .

Well, I am not very familiar with HTML inputs, but I think you should use "multiple" attribute in you SINGLE file input tag.
Or rename "files" to "files[]".
Look at this

try this way if you have multiple file controls on view.
you can even have Guid initialized for each file and can ignore appending i to the name.
public class MultipleFilesForm
{
public HttpPostedFileBase file1 {get;set;}
public HttpPostedFileBase file2 {get;set;}
}
action method as
public ActionResult Home(MultipleFilesForm form)
{
var guid = Guid.NewGuid().ToString();
someclass.filename = guid;
int i = 0;
if(form.file1 != null)
{
var file = form.file1;
if (file.ContentLength > 0)
{
var fileName = guid + i.ToString() + Path.GetExtension(file.FileName));
var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
file.SaveAs(path);
i++;
}
}
if(form.file2 != null)
{
//handle file
}
...
}
[UPDATE]
try this way
try this as well.
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null && file.ContentLength > 0)
{
var fileName = guid + i.ToString() + Path.GetExtension(file.FileName));
var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
file.SaveAs(path);
i++;
}
}

Related

Upload image path-name is "System.Web.HttpPostedFileWrapper"

"ilan" is a table in my database, ilan has a column named "kapak_foto".
Here is my code:
[HttpPost]
[ValidateInput(false)]
public ActionResult ilanver(ilan ilan,HttpPostedFileBase kapak_foto)
{
if (kapak_foto != null)
{
string kapakname = Path.GetFileNameWithoutExtension(kapak_foto.FileName)
+ "-" + Guid.NewGuid() + Path.GetExtension(kapak_foto.FileName);
Image orjres = Image.FromStream(kapak_foto.InputStream);
orjres.Save(Server.MapPath("~/Content/images/pics" + kapakname));
ilan dbres = new ilan();
dbres.kapak_foto = "/Content/images/pics" + kapakname;
}
The html part:
#using (Html.BeginForm("ilanver", "ilanver", FormMethod.Post, new { enctype="multipart/form-data" }))
{ <input type="file" name="kapak_foto"/>}
Firstly; the code is
orjres.Save(Server.MapPath("~/Content/images/pics/" + kapakname));
Second; if you will use the path of saved file, you must take the file location into antoher variable before to save;
var filePath = "/Content/images/pics/" + kapakname;
orjres.Save(Server.MapPath(filePath));
ilan dbres = new ilan();
dbres.kapak_foto = filePath;
// ... the other codes...
db.ilan.add(dbres); // if your databse name defined before as db!
db.SaveChanges();
If the filePath is correct for to save file, it can be usable for url.

Update model property in Asp.net mvc kendo ui async file upload

I have a kendo ui async file upload with the following options on my view.
<div class="demo-section">
#(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("Save", "Upload")
.AutoUpload(true)
)
)
</div>
In the corresponding action method ,I would like to set my model's properties for filename .Shown below is what i have currently .
public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
{
// The Name of the Upload component is "files"
if (files != null)
{
foreach (var file in files)
{
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
// The files are not actually saved in this demo
// file.SaveAs(physicalPath);
}
}
// Return an empty string to signify success
return Content("");
}
If there is a way to do it ,please let me know ..
public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
{
var savedFilePaths = new List<string>();
var applicationPath = System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Authority + System.Web.HttpContext.Current.Request.ApplicationPath + "/Content/Images/Others/";
// The Name of the Upload component is "files"
if (files != null)
{
foreach (var file in files)
{
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
if (fileName != null)
{
fileName = DateTime.Now.ToString("yyyyMMddmm-") + fileName;
var physicalPath = Path.Combine(Server.MapPath("~/Upload/Hotel"), fileName);
file.SaveAs(physicalPath);
savedFilePaths.Add(applicationPath + fileName);
}
}
}
// Return an empty string to signify success
return Content("");
}

How to upload multiple files in mvc 5 to server and store file's path with Entity Framework

I am trying to save a list of files to the file system and the path to EF. I haven't found a complete tutorial online so I've mashed up a couple of blog posts to scope out what I need. I can save 1 file but I can't save multiple files. I know why though. It is because the list gets reinitialized after every file. I've tried to move things in and out of scope and tried initializing variables in other ways. Can someone take a look at my controller and see what I can do to fix?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = "Id")] Incident incident, IEnumerable<HttpPostedFileBase> upload)
{
if (ModelState.IsValid)
{
if (upload != null)
{
int MaxContentLength = 1024 * 1024 * 10; //10 MB
string[] AllowedFileExtensions = new string[] { ".jpg, ", ".gif", ".png", ".pdf", ".doc", "docx", "xls", "xls" };
foreach (var file in upload)
{
if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf(".", StringComparison.Ordinal)).ToLower()))
{
ModelState.AddModelError("Upload", "Document Type not allowed. Please add files of type: " + string.Join(", ", AllowedFileExtensions));
}
else if (file.ContentLength > MaxContentLength)
{
ModelState.AddModelError("Upload", "Your file is too large. Maximum size allowed is: " + MaxContentLength + " MB");
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
var photo = new FilePath
{
FileName = Path.GetFileName(file.FileName),
FileType = FileType.Document
};
incident.FilePaths = new List<FilePath> { photo };
}
}
ModelState.Clear();
}
db.Incidents.Add(incident);
db.SaveChanges();
return RedirectToAction("Index");
}
Initialize the list before loop:
incident.FilePaths = new List<FilePath>();
foreach(var file in upload)
{
// your code except last line
incident.FilePaths.Add(photo);
}
// rest of your code

Request.Files - get the first File without foreach cycle

I'm new in web. This is my action:
[HttpPost]
public virtual ActionResult SaveFile(IEnumerable<VacationSchedule.Models.VacationTypeViewModel> vacationTypes)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
string type = file.ContentType;
string nameAndLocation = "~/Documents/" + System.IO.Path.GetFileNameWithoutExtension(file.FileName);
file.SaveAs(Server.MapPath(nameAndLocation));
}
return View(MVC.Admin.ActionNames.Documents);
}
Question: I know that in the Request.Files can be only one file. Is exist any way to get this File without foreach cycle?
Get the index/key of first element with the name of file:
var imagem = Request.Files[Request.Files.GetKey(0)];
You can use the FirstOrDefault extension method:
string fileName = Request.Files.Cast<HttpPostedFile>().FirstOrDefault();
if (!string.IsNullOrEmpty(fileName))
{
}
Or simply the ternary operator with the index accessor:
string fileName = Request.Files.Count > 0 ? Request.Files[0] : null;

Path issues in File upload ?

I am trying to implement a simple file upload, but having some troubles. When I hard-code the path it works fine. But for some reason, when I try to use a file upload, the controller name is being appended to the path
Hard coded path (what I'm trying to get):
#"C:\Users\Scott\Documents\The Business\MasterSpinSite\MasterSpin\MasterSpin\LOADME.txt"
Path I am getting an exception with (notice the "appz" controller name):
C:\Users\Scott\Documents\The Business\MasterSpinSite\MasterSpin\MasterSpin\appz\LOADME.txt'
My Controller
public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
string filePath = Request.MapPath(file.FileName);
string input = System.IO.File.ReadAllText(filePath);
string[] lines = Regex.Split(input, "#!#");
// ...... do stuff
}
My View
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" value="LOAD ME!">
</form>
What could be causing this behavior ?
You can save yourself the effort of the streams:
string filename = Request.Files["file"].FileName;
string filePath = Path.Combine(Server.MapPath("~/YourUploadDirectory"), filename);
HttpPostedFileBase postedFile = Request.Files["file"] as HttpPostedFileBase;
postedFile.SaveAs(filePath);
string input = File.ReadAllText(filePath);
try this:
public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)
if (file.ContentLength > 0)
{
var filePath = System.IO.Path.GetFileName(file.FileName);
using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
{
var input = sr.ReadToEnd();
var lines = Regex.Split(input, "#!#");
}
}
}
(bug) System.IO.Path.GetFileName(file.FileName) return the name of file
Edit
change System.IO.Path.GetFileName(file.FileName) for Server.MapPath(file.FileName)
public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)
if (file.ContentLength > 0)
{
var filePath = Server.MapPath(file.FileName);
using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
{
var input = sr.ReadToEnd();
var lines = Regex.Split(input, "#!#");
}
}
}
Edit II
or copy to diferent path:
public ActionResult Load(spinnerValidation theData, HttpPostedFileBase file)
if (file.ContentLength > 0)
{
var fileName = System.IO.Path.GetFileName(file.FileName);
var fileUpload = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(fileUpload);
if (System.IO.File.Exists(fileUpload))
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileUpload))
{
var input = sr.ReadToEnd();
var lines = Regex.Split(input, "#!#");
}
}
}
}

Categories