Muhannad Hassan Muhannad Hassan - 6 months ago 33
Javascript Question

upload a file and save it in a temporary folder

I have the following method that uploads a file:

[HttpPost]
public ActionResult Upload()
{

string directory = @"C:\Temp\";

HttpPostedFileBase file = Request.Files["file"];

if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);

file.SaveAs(Path.Combine(directory, fileName));
}
return RedirectToAction("Index");
}


and here is my ajax call:

$('#uploadButton').on('click', function()
{

$.ajax({
type: "POST",
dataType: 'json',
url: '@Url.Action("Upload", "Application")',
timeout: 2000,
contentType: 'application/json',
success: function (data) {

//show content
alert('Success!')
}
});
}
)


I need to send the "Request.files["file"]" with the uploaded file.

Here is the form where my code is located :

<form action="/profile/upload" method="post" enctype="multipart/form-data">

<div class="form-group">

<label>File</label>

<input type="file" name="file" id="file" class="form-control" />
<br />
<input type="button" id="uploadButton" value="Upload" />
</div>
</form>

Answer

try this :

    $('#uploadButton').on('click', function () {
    var data = new FormData();
    var files = $('[type="file"]').get(0).files;
    // Add the uploaded image content to the form data collection
    if (files.length > 0) {
        data.append("file", files[0]);
    }

    $.ajax({
        type: "POST",
        url: '@Url.Action("Upload", "Application")',
        type: 'POST',
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            //show content
            alert('Success!')
        }
    });

})
Comments