I am embarking on my first attempt at uploading files through Ajax and .ashx. My browser of choice is FireFox 75.0. Upon inspecting the web console, I set a Breakpoint on
frm.append(files[i], files[i].name);
. I can see the files being appended to the FormData() object in my script. The file input control (HTML5) triggers a JavaScript event with an "onchange" attribute. The JavaScript functionality appears to be working as expected. However, my handler file is not able to detect the HttpFileCollection. I am puzzled by this issue and seeking assistance to resolve it.
Below is the code snippet from the ASPX page:
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link href="../../assets/css/bootstrap.css" rel="stylesheet" />
<link href="../../assets/css/OLF_style.css" rel="stylesheet" />
<script type="text/javascript" src="../../scripts/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../../scripts/bootstrap.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div class="row" id="rw_5887" style="border-bottom: 1px inset #e0e0e0;">
<div class="col-sm-3 txtmd txright" style="padding: 4px 10px 4px 4px;color:#333333"><label for="DocUpload">Upload File</label></div>
<div class="col-sm-9 txtmd" style="padding: 4px 4px 4px 4px;;color:#999999"><img id="upload_files" src="../../assets/img/btn_upload01.png" alt="Upload File" style="margin: 7px 10px 0px 10px" /><input id='fupDocUpload' type='file' accept=".docx;.doc" multiple='multiple' class='form-control' style='display:none;height:0px;width:0px' onchange="doFileSelect();" /><div id="uploadstatus" style="display: inline"></div>
<br /><progress id="fileProgress" style="display: none"></progress>
<br /><div id="dvFileUploads" class="gradlt txtreg rnd" style="height: 60px;width:90%;"></div><input type="hidden" id="hfFilesUploaded" />
</div>
</div>
</form>
<script type="text/javascript">
var fileupload = $("#fupDocUpload");
var imgbtn = $("#upload_files");
imgbtn.click(function () {
$(fileupload).click();
});
function doFileSelect() {
$("#uploadstatus").html('Upload in progress...');
var fileInput = $('#fupDocUpload').get(0);
var frm = new FormData();
var files = [];
files = fileInput.files;
var ufiles = $("#hfFilesUploaded").val();
for (var i = 0; i < files.length; i++) {
frm.append(files[i], files[i].name);
if ($("#hfFilesUploaded").val() == '') {
$("#dvFileUploads").append(files[i].name);
$("#hfFilesUploaded").val(files[i].name);
} else {
$("#dvFileUploads").append(', ' + files[i].name);
$("#hfFilesUploaded").val(ufiles + ',' + files[i].name);
}
}
$.ajax({
url: 'handler/UploadHandler.ashx',
type: 'POST',
data: frm,
cache: false,
contentType: false,
processData: false,
success: function (result) {
$("#fileProgress").hide();
$("#uploadstatus").html(result);
window.setTimeout(clrStatus, 2000);
},
xhr: function () {
var fileXhr = $.ajaxSettings.xhr();
if (fileXhr.upload) {
$("progress").show();
fileXhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
$("#fileProgress").attr({
value: e.loaded,
max: e.total
});
}
}, false);
}
return fileXhr;
}
});
}
function clrStatus() {
var status = $('#uploadstatus').html('');
}
</script>
</body>
</html>
And here is the code snippet from my handler:
Imports System
Imports System.Web
Imports System.IO
Public Class UploadHandler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/html"
Dim files As HttpFileCollection = context.Request.Files()
Dim UploadPath As String = ConfigurationManager.AppSettings("FormFileUpload")
'Dim strFiles As String = String.Empty
Try
If context.Request.Files.Count = 0 Then
context.Response.Write("<img src=""../../assets/img/NotAllowed.png"" alt="""" style=""margin-left: 5px; margin-right: 5px"" /> No Files Found!")
Else
For i As Integer = 0 To files.Count - 1
Dim file As HttpPostedFile = files(i)
Dim fname As String = String.Empty
fname = file.FileName
fname = Replace(fname, " ", "_") 'Replace spaces in file name
fname = Path.Combine(context.Server.MapPath(UploadPath), fname)
file.SaveAs(fname)
Next
context.Response.Write("<img src=""../../assets/img/CkMark.png"" alt="""" style=""margin-left: 5px"" />")
End If
Catch ex As Exception
context.Response.Write("<img src=""../../assets/img/NotAllowed.png"" alt="""" style=""margin-left: 5px; margin-right: 5px"" /> Error!" & ex.ToString())
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Despite my efforts, the Try Catch block in my handler is unable to detect any files, always displaying "No files found!" message. When checking the network tab in the web console, I can see the file objects present - Content-Disposition: form-data; name="[object File]"
The file "Test.docx" is attempted to be uploaded.
I am seeking guidance on resolving this issue. Any help would be greatly appreciated. Thank you!