Abdur Rahim
Abdur Rahim

Reputation: 4021

Get the selected file after browsing file uploader in MVC 4

I am using ASP .Net MVC 4.0, RazorView, C#, VS2010.

I have a html input type='file'. The task is to get the file copied to a certain directory, while user will select the file from file browser.

If i get the full file path, that could solve the problem. But I failed after googling 3+ hours.

If I get the file with jQuery / Javascript and send with ajax to serverside, then it could be solved as well.

I failed both way. Here is some of my code:

function checkFileType() {
    var input = document.getElementById('IDbtnUpload');
    var selected_file = document.getElementById('IDbtnUpload').files[0];

    if (input.value != "") {
        document.getElementById('lblFile').innerHTML = "";
        var file = input.value;
        document.getElementById('hiddenFileName').value = file.toString();
        if ((file.lastIndexOf('xls') == file.length - 3) || (file.lastIndexOf('xlsx') == file.length - 4) || (file.lastIndexOf('csv') == file.length - 3)) {
            alert(file.toString());
            var url = '@Url.Action("ProcessExcel", "NeuGesellschaft")';
            $.post(url, { x: selected_file }, function (data) {
                //$('#textareaReadonly').val(data);
                alert(data);
            });
        }
        else {
            document.getElementById('lblFile').innerHTML = "Incorrect File Format. Please browse an excel/csv file!";
            alert('Incorrect File Format. Please upload an excel/csv file!');
        }
    }
}

I tried to use the $.post to send the file to my server side method.

If anyone suggest how to send file or how to get the full filename (any of this will be appriciated), that will help me.

EDIT 1:

    public string ProcessExcel(object formData)
    {

        return "";
    }

What wil be the data type of my parameter?

Upvotes: 0

Views: 676

Answers (1)

Alex
Alex

Reputation: 11245

$.post(url, { x: selected_file }, function (data) { will just send {x : "[object FileList]"} because files[0] will return FileList. If you want to send file content you need to use FormData for example(with out jQuery):

var fileInputNode = document.getElementById('IDbtnUpload');
var file = fileInputNode.files[0];
var url = '@Url.Action("ProcessExcel", "NeuGesellschaft")';
var xhr = new XMLHttpRequest();
var formData = new window.FormData();

formData.append(fileInputNode.name, file);
xhr.open('POST', url);
xhr.send(formData);

Also you can use jQuery File Upload plugin for file uploading.

Upvotes: 1

Related Questions