I’m writing a C# ASP.Net MVC application for client to post files to other server. I’m using a generic handler to handle posted files from client to server. But in my handler, System.Web.HttpContext.Current.Request.Files always empty (0 count).
Form Code:
@model ITDB102.Models.UploadFileResultsModels
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
<h1>Upload File</h1>
<form id="file-form" action="/Files/UploadFile" method="post" data-ajax="false" enctype="multipart/form-data">
<div><input type="file" id="FilePath" name="FilePath"/>
<button type="submit">Send File</button></div>
</form>
</div>
@section scripts{
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
// Variable to store your files
var files;
var form = document.getElementById('file-form');
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event) {
files = $('#FilePath').get(0).files;
}
form.onsubmit = function (event) {
uploadFiles(event);
}
// Catch the form submit and upload the files
function uploadFiles(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// Create a formdata object and add the files
var data = new FormData();
if (files.lenght > 0)
{
data.append('UploadedFiles', files[0], file[0].name);
}
//setup request
var xhr = new XMLHttpRequest();
//open connection
xhr.open('POST', '/Files/UploadFile',false);
xhr.setRequestHeader("Content-Type", files.type);
//send request
xhr.send(data);
}
</script>
}
Handler:
/// <summary>
/// Uploads the file.
/// </summary>
/// <returns></returns>
[HttpPost]
public virtual ActionResult UploadFile()
{
HttpPostedFile myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"];
bool isUploaded = false;
string message = "File upload failed";
if (myFile != null && myFile.ContentLength != 0)
{
string pathForSaving = Server.MapPath("~/Uploads");
if (this.CreateFolderIfNeeded(pathForSaving))
{
try
{
myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
isUploaded = true;
message = "File uploaded successfully!";
}
catch (Exception ex)
{
message = string.Format("File upload failed: {0}", ex.Message);
}
}
}
return Json(new { isUploaded = isUploaded, message = message }, "text/html");
}
#region Private Methods
/// <summary>
/// Creates the folder if needed.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
private bool CreateFolderIfNeeded(string path)
{
bool result = true;
if (!Directory.Exists(path))
{
try
{
Directory.CreateDirectory(path);
}
catch (Exception)
{
/*TODO: You must process this exception.*/
result = false;
}
}
return result;
}
#endregion
Please help me. Thanks.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Finally, I found the problem.
The code var myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"]; in my controller is never working for some reason. There is nothing wrong with my ajax.
I changed my code in the controller as bellow and it’s working find now.
[HttpPost]
public virtual ActionResult UploadFile()
{
//var myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"];
//
bool isUploaded = false;
string message = "File upload failed";
for (int i = 0; i < Request.Files.Count; i++ )
{
var myFile = Request.Files[i];
if (myFile != null && myFile.ContentLength != 0)
{
string pathForSaving = Server.MapPath("~/Uploads");
if (this.CreateFolderIfNeeded(pathForSaving))
{
try
{
myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
isUploaded = true;
message = "File uploaded successfully!";
}
catch (Exception ex)
{
message = string.Format("File upload failed: {0}", ex.Message);
}
}
}
}
return Json(new { isUploaded = isUploaded, message = message }, "text/html");
}
#endregion
#region Private Methods
/// <summary>
/// Creates the folder if needed.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
private bool CreateFolderIfNeeded(string path)
{
bool result = true;
if (!Directory.Exists(path))
{
try
{
Directory.CreateDirectory(path);
}
catch (Exception)
{
/*TODO: You must process this exception.*/
result = false;
}
}
return result;
}
#endregion
}
Method 2
You need to set following for xhr.
dataType: 'json', contentType: false, processData: false,
See help link – File upload using MVC 4 with Ajax
I see that, you have included jquery library and used jquery selectors, so why don’t you use $.ajax for POST request? In case you are interested in jquery way, following is the script.
$.ajax({
type: "POST",
url: '/Files/UploadFile',
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function(response) {
alert('succes!!');
},
error: function(param1,param2,param3) {
alert("errror");
}
});
Method 3
I had a similar issue using Asp.Net MVC5. For me it turned out to be a file size issue which I resolved following suggestions from this posted question.
Method 4
To post a file, the post data must be in multipart/form-data Encoding type. So you must set request header as below:
xhr.setRequestHeader(“Content-Type”,”multipart/form-data”);
Please see sample: Upload File With Ajax XmlHttpRequest
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0