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;
Related
I am attempting to add the contents of an IEnumerable to a StringBuilder as it works its way through a file, or files. Currently my controller has two methods.
Method 1 provides a way for me to find the chunk of data that I want to extract from a file:
public static IEnumerable<string> GetData(string fileName, string startLine, string endLine)
{
var found = false;
foreach (var line in System.IO.File.ReadLines(fileName))
{
if (line == startLine) found = true;
if (!found) continue;
yield return line;
if (line == endLine) break;
}
}
Method 2 is my action result in which I call the IEnumerable and try to add it to my StringBuilder.
string[] files = Directory.GetFiles(path, fileName);
string startLine = "foo";
string endLine = "bar";
StringBuilder blog = new StringBuilder();
foreach (string file in files)
{
var blob = GetData(file, startLine, endLine);
foreach (var item in blob)
{
blog.Append(item);
}
}
var test = blog; //used to test
If I step through using my VS debugger I can see that Method 1 is being hit and that it reads through the lines when it is called. However, blog remains empty both inside and outside of the foreach loop.
How do I put the contents of IEnumerable<string> GetData() into my StringBuilder?
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++;
}
}
I want to remove number from Extension with string in C#.
For Example : "Url1234.pdf" I want the last answer looks like "Url.pdf"
Thank you for your Contribution
var fileName = "";
if (file != null && file.ContentLength > 0)
{
fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName); //Path.GetFileName(file.FileName);
var extension = System.IO.Path.GetExtension(file.FileName);
DBConnect.OpenDB();
DBConnect.DbSelect("select MAX(ID) as ID from tblFileUpload");
if(DBConnect.dr.Read())
{
fileName += DBConnect.dr["ID"].ToString();
}
DBConnect.CloseDB();
var path = Path.Combine(Server.MapPath("~/File/"), fileName+extension);
new FileUploadLayer().save("aa", fileName, file.ContentLength);
file.SaveAs(path);
UploadFile("aa");
}
I save a file with the extension(.pdf). That file name has numbers also.(Url1234.pdf).So, when i call it back i need to remove those numbers and only need the string part (Url.pdf).
You can use regex as shown or a simple LINQ query, i'd also recommend System.IO.Path:
string originalPath = "Url1234.pdf";
string dir = Path.GetDirectoryName(originalPath); // in this case ""
string extension = Path.GetExtension(originalPath); // .pdf
string fn = Path.GetFileNameWithoutExtension(originalPath); // Url1234
string newFn = String.Concat(fn.Where(c => !Char.IsDigit(c))); // Url
string newPath = Path.Combine(dir, newFn + extension); // Url.pdf
You can use Regex to replace numbers with empty string:
var result1 = Regex.Replace("Url1234.pdf", #"[\d-]", string.Empty);
Add using System.Text.RegularExpressions;
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("");
}
this is my code in controller
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
string TempPath = Server.MapPath("~/TempImages/");
foreach (HttpPostedFileBase file in files)
{
string filePath = Path.Combine(TempPath, file.FileName);
Tempdata["paths"] =filePath;
}
}
how in insert every time the path and get it as array / arraylist ?
update:
this is what really goes on for every image readed this action is running
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
if (!Directory.Exists(Server.MapPath("~/TempImages/")) || files !=null)
{
string TempPath = Server.MapPath("~/TempImages/");
List<string> paths = new List< String> ();
foreach (HttpPostedFileBase file in files)
{
string filePath = Path.Combine(TempPath, file.FileName);
System.IO.File.WriteAllBytes(filePath, ReadData(file.InputStream));
file.SaveAs(filePath);
paths.Add(filePath);
TempData["paths"] = paths;
}
}
return view();
}
Can you not just do
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
List<string> paths = new List<string>();
foreach (HttpPostedFileBase file in files)
{
string filePath = Path.Combine(TempPath, file.FileName);
paths.Add (filePath);
}
Tempdata["paths"] = paths;
}