-->

Sunday, April 20, 2014

How to Serve Files to User in Asp.Net MVC

Let the user download a file from server is not a typical task, programmer have to write some lines of code which will execute the task. Asp.Net MVC action with returning type FileResult will complete this task in few task listed in the article.

After uploading file/files on the server, how to deliver/serve a file for user to download and save on an individual system depends on the way of storing the file on the server by programmer. Programmer can provide a simple link to an action including some lines of code to perform the task.

In the controller write below line of c# code in the action named “DownloadFile” which will access the file saved on the root of this project and then prompt user to Open/Save that file.

public FileResult DownloadFile()
{
var file = Server.MapPath("~/download file.txt");
return File(file, "Text", "download file");
}

These two line of code will sufficient to prompt the user, now in view page create an actionline which will redirect the user to this action. The second line of code will creates a System.Web.Mvc.FilePathResult object by using the file name, the content type, and the file download name.

@Html.ActionLink("Download File", "DownloadFile");

Run the project and particular controller/action then click on the link created above. This will show an opening download file window having two option to open or save that file, as shown in the below image:

How to Serve Files to User in Asp.Net MVC

Saturday, April 19, 2014

How to Validate File or File type in Java Script MVC

Programmer need to check whether the file is selected by the user or not, when uploading a file. If user will not upload any file and submit the form, the code will throw an exception with description like "file must not be null".

To overcome this issue programmer have to check the uploaded file before the form submission, and this can be performed by using Java script. Write the following code in our view where the file upload control is placed:

function validateForm() {
if ($("#file").val() == "") {
alert("Please select a file");
return false;
}
}

Here “#file” is the id of file upload control and we are checking the value of this control. If the value is empty then it will alert with the message shown and return back to the form. If this control will have file then it will submit the form. On the submit button, just call this function to execute this code with Onclick=”validateForm();”.

Now to select only some file types write another function as below:

function checkfile(sender) {
        var validExts = new Array(".jpeg", ".jpg", ".png");
        var fileExt = sender.value;
        fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
        if (validExts.indexOf(fileExt) < 0) {
            alert("File must of types \".jpeg\", \".jpg\", \".png\");
            $("#file").val('');
            return false;
        }
        else return true;
    }

This function will be called on OnChange event of the file upload control. It will show an alert message written above if the type of selected file will not be in the list declared in the function. Write CheckFile(this) in onChange event of the file upload control.

In this function we are checking only the extension of the selected file, extension may be found by any individual logic. Earlier article was about to uploading file, this java script will not submit the form if user will not select any file through the file upload control.

How to Upload File/Files in Asp.Net MVC

Uploading a file is need some Html code with setting the encoding type to multipart/form-data and the method of form is post. After setting this type, programmer have to use file upload control having the property name and id. Here is the code written in the view page:

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <input type="file" name="file" id="file"/>
</div>
<input type="submit" value="Upload" />
}

This code will place a file upload control to browse a single file of any type of extension and a submit button which will help to post this file to action. Now our action method must have a specific parameter written below in the code:

public ActionResult GetValues(HttpPostedFileBase file)
{
var fileName = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(Server.MapPath("Path/"), fileName);
file.SaveAs(path);
…………
………..

In this action method programmer can easily get this file and can save this file as done in above code. This code is for uploading/accessing single file, what if programmer want to upload multiple files.

To upload multiple files in view page, just change the file upload control as written below:

<input type="file" name="files" id="files" multiple/>

In the action method of controller change the parameter as written below:

public ActionResult GetValues(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{

}
……..
……..
All the files can easily accessed and using the foreach loop, programmer can perform individual action with these files. If programmer want to limit the no. of files to be uploaded by the user, no. of file upload control can be used in the view page and action code will remain same as is.

What if two files are uploaded with the same name, the previous file will be overwritten by the new one. To overcome with these issues we can rename the file when we are saving them like unique identifier or may be other unique name. Programmer can also perform some validation discussed earlier.

Thursday, October 17, 2013

How to Copy File from One Location to Another: Windows Forms

Sometimes, some files are mostly used in our programming field, and we can’t use OpenFileDialog only after a minute and so on. That’s why we have to copy these files in our desired location, so that we can use them as per our requirement.

To copy a file from an existing location, we should have source path and destination path. For source path, we can use open file dialog and for destination path, we can use folder browsing path or even a path in form of string.

Generally System.IO.File namespace is used for handling file functions and events. In our previous post we have create, delete, read or write a text file. Now to copy a file from source to destination, we are just using following function:

System.IO.File.Copy("Source Path", "Destination Path", Boolean value);

This function is as simple as written above. Source and destination path is known to everyone, now the focus is on Boolean value. This Boolean parameter is deciding, whether the file should be overwriten or not. If the value of this Boolean value be
  • True: if the file exist on destination, it will overwrite that. If not exist copy that file.
  • False: if the file exist on destination, it will not copy. If not exist copy that file.
Now look out the following code, it will open an open file dialog, and then copy the selected file to our debug folder of the project.
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
System.IO.File.Copy(ofd.FileName, Environment.CurrentDirectory + "\\"+ ofd.SafeFileName, true);

I have used the true value for Boolean parameter, means it will overwrite the file if exists. So the file has been successfully copied and we can check that using File.Exist(“Path”) function.
© Copyright 2013 Computer Programming | All Right Reserved