Httpcontext.Current.Request.Files Is Always Empty

Request.Files is always null

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

}

HttpRequest.Files is empty when posting file through HttpClient

You shouldn't use HttpContext for getting the files in ASP.NET Web API. Take a look at this example written by Microsoft (http://code.msdn.microsoft.com/ASPNET-Web-API-File-Upload-a8c0fb0d/sourcecode?fileId=67087&pathId=565875642).

public class UploadController : ApiController 
{
public async Task<HttpResponseMessage> PostFile()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

try
{
StringBuilder sb = new StringBuilder(); // Holds the response body

// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);

// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
sb.Append(string.Format("{0}: {1}\n", key, val));
}
}

// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
}
return new HttpResponseMessage()
{
Content = new StringContent(sb.ToString())
};
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}

}

HttpContext.Current.Request.Files Always Null in WCF [save image with original metadata]

Finally, My issue resolved with the help of given link

Me written below code in my implementation, I just downloaded MultipartParser.cs class from the codeplex, moreover I am pasting here complete class because Codeplex is going down after some time.

public string Upload(Stream data)
{
MultipartParser parser = new MultipartParser(data);

if (parser.Success)
{
// Save the file
string filename = parser.Filename;
string contentType = parser.ContentType;
byte[] filecontent = parser.FileContents;
File.WriteAllBytes(@"C:\test1.jpg", filecontent);
}
return "OK";
}

MultipartParser.cs Class:

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

/// <summary>
/// MultipartParser http://multipartparser.codeplex.com
/// Reads a multipart form data stream and returns the filename, content type and contents as a stream.
/// 2009 Anthony Super http://antscode.blogspot.com
/// </summary>
namespace WcfService1
{
public class MultipartParser
{
public MultipartParser(Stream stream)
{
this.Parse(stream, Encoding.UTF8);
}

public MultipartParser(Stream stream, Encoding encoding)
{
this.Parse(stream, encoding);
}

public static async Task ParseFiles(Stream data, string contentType, Action<string, Stream> fileProcessor)
{
var streamContent = new StreamContent(data);
streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);

var provider = await streamContent.ReadAsMultipartAsync();

foreach (var httpContent in provider.Contents)
{
var fileName = httpContent.Headers.ContentDisposition.FileName;
if (string.IsNullOrWhiteSpace(fileName))
{
continue;
}

using (Stream fileContents = await httpContent.ReadAsStreamAsync())
{
fileProcessor(fileName, fileContents);
}
}
}

private void Parse(Stream stream, Encoding encoding)
{
this.Success = false;

// Read the stream into a byte array
byte[] data = ToByteArray(stream);

// Copy to a string for header parsing
string content = encoding.GetString(data);

// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");

if (delimiterEndIndex > -1)
{
string delimiter = content.Substring(0, content.IndexOf("\r\n"));

// Look for Content-Type
Regex re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = re.Match(content);

// Look for filename
re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);

// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success)
{
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();

// Get the start & end indexes of the file contents
int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;

byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
int endIndex = IndexOf(data, delimiterBytes, startIndex);

int contentLength = endIndex - startIndex;

// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];

Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);

this.FileContents = fileData;
this.Success = true;
}
}
}

private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)
{
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);

if (startPos != -1)
{
while ((startPos + index) < searchWithin.Length)
{
if (searchWithin[startPos + index] == serachFor[index])
{
index++;
if (index == serachFor.Length)
{
return startPos;
}
}
else
{
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1)
{
return -1;
}
index = 0;
}
}
}

return -1;
}

private byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}

public bool Success
{
get;
private set;
}

public string ContentType
{
get;
private set;
}

public string Filename
{
get;
private set;
}

public byte[] FileContents
{
get;
private set;
}
}
}

context.Request.Files[0] is empty in FireFox,

You have to include "runat='server'" attribute to your input file

example:

 <input type="file" id="myfile1" runat="server" >


Related Topics



Leave a reply



Submit