I am working in C# WebForms. I have written a file uploader functionality. Once a file is selected an AJAX call from javascript will be made to a generic handler(ashx file). When the file is uploaded without any error I am getting the "File was uploaded successfully!" message sent by the handler as expected. However, when an error happens I am getting an "Internal Server Error". I would like to have the specific error message I am sending from the handler in the catch block.
Code in aspx page:
function uploadFile(file, i) {
alert("Inside uploadFile");
var formData = new FormData();
formData.append(file.name, file);
$.ajax({
url: "FileUploadHandler.ashx",
type: "POST",
contentType: false,
processData: false,
data: formData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
Code in ashx file:
public class FileUploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
try
{
UploadSelectedFile(file);//a method call which uploads the file
context.Response.ContentType = "text/plain";
context.Response.Write("File was uploaded successfully!");
}
catch (Exception ex)
{
context.Response.ContentType = "text/plain";
context.Response.Status = "Could not upload file. Reason: " + ex.Message;
}
finally
{
}
}
}
}
}