MVC Get File Path from file selector - asp.net-mvc

In MVC looking for a way to select a file from a browse/file selector, and then hit submit.
But when I hit submit I don't want to upload the actual file, just want to store/retrieve the filepath selected.
Looking at examples like this, it seems like the file gets uploaded and stored into memory which is not what I want.
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{

You can use Path.GetFileName method to get the file name with extension. GetFileName method accepts the full path to the file, which you can obtain from the FileName property of the posted file.
If you do not want to save it to sever disk, Don't do that. Just read the file name and do what you want to do with that.
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null)
{
string justFileName=Path.GetFileName(file.FileName);
// No need to save the file. Just forget about it. You got your file name
//do somethign with this now
}
// TO DO : Return something
}
You need to import System.IO namespace to your class to use the Path class.

On the client capture the name of the file that the user selected and place it in a hidden file. When the user clicks submit, only submit the file name to an action method that takes string as input:
[HttpPost]
public ActionResult Index(string filename)
{
//Do something
}
Since you did not provide code on how you are selecting the file, I can only suggest that you use a plugin that allows you to hook in your own javascript for the selection event (I use KendoUI Upload).

Related

caching forms for different requests

I am working on a MVC4 application with Razor.
users will be able to edit entities on this page, but since MVC-style urls look like this:
~/{Entity}/Edit/{Id}
~/MyEntity/Edit/1
~/MyEntity/Edit/2
I fear that the client will not load the form from the cache.
i am currently always responding the empty form and filling data later with an ajax request. I'd love to keep the url style and somehow tell the client that he already got the form (from a request with different Id)
You can add another parameter to your controller actions
for example right now you have
~/MyEntity/Edit/1
so i am assuming it looks something like
public ActionResult Edit(int id)
you can simply add another parameter:
public ActionResult Edit(int id, int loadFromCache)
{
if(loadFromCache == 1)
{
//do something
}
else
{
//proceed regularly
}
}
this way you can pass another parameter by which you will be able to do an if statement
~/MyEntity/Edit/1?loadFromCache=1

Set file control value from model in asp.net mvc3 razor

In my MVC application, I am using following code for a file.
MODEL
public HttpPostedFileBase File { get; set; }
VIEW
#Html.TextBoxFor(m => m.File, new { type = "file" })
Everything working fine .. for submitting value But I am trying to load file from controller model which is not working
CONTROLLER
public ActionResult ManagePhotos(ManagePhoto model)
{
if(ModelState.IsValid)
{
//upload file
}
else
{
return View(model); //contains type HttpPostedFileBase File { get; set; }
}
}
how can i load file input again if my validation fails as after returning, my file control is not mapped to model to file and it's empty...
If you know that the file is valid, and want to keep it temporarily, you can keep it in session (but be aware of memory usage).
If you know the file is valid, and want to keep it permanently, save it and just keep the path in memory.
If you know that the file is invalid, you wont want to nor often be able to keep it.
Often this is treated in the same way during validation failure as a password - it needs to be provided again and as such is requested for only when everything else is good.
if you want to go as far as it takes to made user experience seamless, then try following:
Add javascript on the client side to validation the user inputs
On the server side temporarily store all the files on the tmp file storage. Clean up files older than 10 minutes. Do this when you need to save files into the storage

asp.net mvc FileStreamResult

First part of question:
I have information in DB and I want to get it from db and save it as .txt file to client.
I have done it with Regular asp.net. but in mvc not yet. My information is not an image. This information about peoples
I watched to This site
Second part of question:
I want to download file to client. There is not problem when downloading one file, but I want to download 3 file at once time with 1 request. But it could not be done. So I decided to create zip file and generate link. When user will click to link it will download to user.
What you think? Is it good to do it with this way?
Third part of question:(new)
How i can delete old .zip files from catalog after succes download? or another way. Lets say with service which will run on server.
You could have the following controller action which will fetch the information from the database and write it to the Response stream allowing the client to download it:
public ActionResult Download()
{
string info = Repository.GetInfoFromDatabase();
byte[] data = Encoding.UTF8.GetBytes(info);
return File(data, "text/plain", "foo.txt");
}
and in your view provide a link to this action:
<%= Html.ActionLink("Downoad file", "Download") %>
You can delete the temporary file returned by using an Action Filter like this. Then apply the attribute to your MVC action method.
public class DeleteTempFileResultFilter : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
string fileName = ((FilePathResult)filterContext.Result).FileName;
filterContext.HttpContext.Response.Flush();
filterContext.HttpContext.Response.End();
System.IO.File.Delete(fileName);
}
}

How to make an MVC AttributeFilter to verify posted file extension

I have a controller that handles file uploads. Ultimately I would like to be able to create attribute to decorate my controller actions like [HttpPostedFileType("zip")] or something similar.
Currently I created this extension method which I use in the action.
public static string GetFileExtension(this HttpPostedFileBase file)
{
if (!file.FileName.Contains('.'))
throw new FormatException("filename does not contain extension");
return file.FileName.Split(".".ToCharArray()).Last();
}
The action signature is
[HttpPost]
public ActionResult Shapefile(HttpPostedFileBase file)
{
file.GetFileExtension()
...
}
I started to create a HttpPostedFileTypeAttribute and was thinking I'd override the OnActionExecuting method and call the extension. In this case with posted files, I can get the Http request and loop over the files but with mvc's model binding having a HttpPostedFileBase or an enumeration of those is much cleaner than the asp 1.x way of getting to the files.
My question is, can I get the parameters in the attribute on action executing or have they not been bound yet since the life cycle hasn't hit the action method yet? Should I create a model with a HttpPostedFileBase property and create a validation attribute? Recommendations?
filterContext has a ActionParameters dictionary. I can just use that.

Pass HttpPostedFileBase as an Argument

I have an application that allows users to upload word and pdf documents. I also have a class in my model that gathers some metadata about the file (i.e., file size, content type, etc.).
I want to centralize some of the "save" functionality (both saving the metadata to the database, and saving the actual file to the server). I would like to pass the HttpPostedFileBase to my Service layer that will then use the built-in .SaveAs(filename) functionality. However, I can't seem to figure out how to pass the file type to another method. I've tried the below:
public ActionResult Index(HttpPostedFileBase uploadedDocument)
{
string fileName = "asdfasdf";
SomeClass foo = new SomeClass();
//this works fine
uploadedDocument.SaveAs(fileName)
//this does not work
foo.Save(uploadedDocument, fileName);
}
public class SomeClass
{
public void Save(HttpPostedFile file, string fileName)
{
//database save
file.SaveAs(fileName);
}
}
When I try to pass the HttpPostedFile into the Save method on SomeClass, there is a compiler error (because in the above, uploadedDocument is of type HttpPostedFileBase, not HttpPostedFile).
However, if I try to cast uploadedDocument to HttpPostedFile, it does not work.
So, specifically, how can I pass an HttpPostedFileBase to another method? Or, more generally, if I were to pass the HttpPostedFileBase.InputStream to another method, how can I save that document to the server? Note that the document is not an image and I am not streaming the response to the user, so writing to the response stream isn't appropriate...I think.
You should just use HttpPostedFileBase, for example in the SomeClass.Save method. The HttpPostedFile class doesn't actually derive from the HttpPostedFileBase, so you're bound to get the compiler error you noticed. You might also see the documentation for HttPostedFileWrapper which is used for the reverse scenario: passing HttpPostedFile to a method that accepts HttpPostedFileBase.

Resources