asp.net mvc FileStreamResult - asp.net-mvc

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);
}
}

Related

Saving multiple images with size limitation and bootstrap

I have built a simple ASP.NET MVC5 project that acts as a classifieds application for my college's students. I got everything figured out and implemented except for the images. I am struggling to find the best approach to store the images.
I came up with the following structure:
Ad represents the advertisement model
adImage represents an image(s) for an ad. AdImage has a foreign Key public int AdId { get; set; } and then public virtual Ad TheAdvertisement { get; set; }
Considerations:
I am using bootstrap
I will not consider support older IE browsers
I have to resize the images prior to save
I will be saving the images on the file system and then store their urls back into my database.
I think I know how to upload then store multiple images. I am struggling with how to implement size-limitation validation to my controller and whether it is something I should consider to implement in my project. What is the best approach when dealing with images in classified website?
To Limit the size of image files, take a look at file size upload limitation in ASP.NET MVC that employs web.config file to meet your purpose.
Another way to Limit file size is writing code something like this:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
//you can put your existing save code here
if (file != null && file.ContentLength > 10000)
{
//do whatever you want with the file
}
}
And the page File Upload ASP.NET MVC 3.0 contains good samples for you if you don't know how to write a controller to save files on file system.

MVC Get File Path from file selector

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).

Umbraco Intercept CMS activities

With Umbraco, is there any way to trigger within code any time a field is updated in a document?
I have an umbraco api that is using data that is stored in a table structure. This data is only used for calculations and not exposed directly on any page, but I want the back end users to be able to modify it. I have code that will take a CSV file and upload the data to the table. I've created a data type that only has one field that is an Upload field. I want to trigger the table update whenever that file is updated. The alternative is to have some sort of filewatcher monitoring the media folder for this particular file, this is the way I'm leaning if umbraco doesn't have a solution.
Yes, there is an API available which you can use.
For Umbraco v6.1+ refer to the Saved event in the ContentService, as described here.
You can register your own event handler using the ApplicationEventHandler interface:
public class RegisterEvents : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
Document.Saved += DocumentSaved;
}
private void DocumentSaved(Document sender, PublishEventArgs e)
{
// check your document type and fields to see if it has changed
}
}

ASP.NET MVC Read Raw JSON Post Data

This is driving me crazy. I'm using ASP.NET MVC. I have a controller with an HttpPost action that acts as a callback URL that is called by another server (not under my control). I want to dynamically read JSON posted to it without using WebAPI or Model Binding. The URL also has a query string parameter passed to it.
The callback URL looks something like this:
http://domain.com/callback?secret=1234
I've tried reading the posted input using:
[HttpPost]
public ActionResult Callback( String secret )
{
String jsonData = new StreamReader(this.Request.InputStream).ReadToEnd();
// ...
}
However "jsonData" is always null or empty.
I just want to get the posted input and stick it into JsonFx so I can dynamically access the contents. Any ideas on how to do this the easiest possible way?
UPDATE
I've discovered the following ...
While the above DOES NOT work (jsonData will be null or empty), the following DOES if I configure what little options I have on the calling server so as to omit the "secret" query string parameter, which is about all I can do on that end since it is not my server. In this case, jsonData will have the correct posted JSON string:
[HttpPost]
public ActionResult Callback( /* String secret */ )
{
String jsonData = new StreamReader(this.Request.InputStream).ReadToEnd();
// ...
}
This is very frustrating to work around and I don't know an easy way to accept both a query string and posted JSON data on a standard MVC controller.
I have a "callback controller" with Action methods that accept various data (via GET, via form POST, via JSON POST, via JSON POST w/ a Query String, etc.) from different third-party servers. These are merchant-type callbacks where I have no control over the formats or methods used to convey information. I just need to accept the callbacks and process the information that should be there.
All of it works fine in my Controller, except the case of "JSON POST w/ a Query String".
This appears (at least to me) to be a shortcoming in standard ASP.NET MVC controllers. ???
Can anyone suggest a solution to this that can be used in a standard ASP.NET MVC controller?
Your initial approach should work if you take into consideration the fact, that ASP.NET MVC model binding has already read the stream, so you should rewind it:
[HttpPost]
public ActionResult Callback(string secret)
{
Request.InputStream.Seek(0, SeekOrigin.Begin);
string jsonData = new StreamReader(Request.InputStream).ReadToEnd();
// ...
}
Reset the position to Zero before reading the stream.
Request.InputStream.Position = 0
For ASP.NET Core 2,this works for me.
[HttpPost]
public ActionResult RawTest() {
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
string content = reader.ReadToEndAsync().Result;
//...
}
//...
}

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

Resources