File upload control using ASP.Net MVC (C#)

HTML code
<input id="file-upload-control" name="UploadFile" type="file"/>
<button id="file-upload-button" class="button tiny" style="border: 1px solid #cccccc;">Upload</button>

JQuery code

var selectedFiles;
$('#file-upload-control').on('change', function (e) {
        selectedFiles = e.target.files;
    });

    $('#file-upload-button').on('click', function () {
        var files = selectedFiles;

        if (files.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < files.length; x++) {
                    data.append("file" + x, files[x]);
                }

                $.ajax({
                    type: "POST",
                    url: 'File/UploadFile',
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (result) {
                        console.log(result);
                        showInfo("File upload was successful! ");
                    },
                    error: function (xhr, status, p3, p4) {
                        var err = "Error " + " " + status + " " + p3 + " " + p4;
                        if (xhr.responseText && xhr.responseText[0] == "{")
                            err = JSON.parse(xhr.responseText).Message;
                        console.log(err);
                        showInfo("Something went wrong uploading file! ");
                    }
                });
            } else {
                alert("This browser doesn't support HTML5 file uploads!");
            }
        }
    });

FileController code

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace DHI.Controllers
{
public class FileController : Controller
{
[HttpPost]
public async Task UploadFile()
{
try
{
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and optionally write the file to disk
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
using (var fileStream = System.IO.File.Create(path))
{
stream.CopyTo(fileStream);
}
}
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Upload failed");
}

return Json("File uploaded successfully");
}
}
}
Advertisements

Author: Harshani Nawarathna

Sri Lankan woman in Computing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s