I am trying to debug an asynchronous file loader that I created some time ago, which no longer works, I have already spent a lot of time without success.
The stream that the server receives is always corrupted, in fact, the file (image) that I save cannot be opened.
To simplify debugging, I created a new ASP.NET project with two main files, an HTML file with a form field and an ASP.NET handler.
Despite the fact that the code here is very trivial, I'm still out of luck !: (
Any help is greatly appreciated, thank you very much!
<!DOCTYPE html> <html> <head> <title>Upload Files using XMLHttpRequest - Minimal</title> <script type="text/javascript"> function uploadFile() { var fd = new FormData(); fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]); var xhr = new XMLHttpRequest(); xhr.addEventListener("load", uploadComplete, false); xhr.addEventListener("error", uploadFailed, false); xhr.addEventListener("abort", uploadCanceled, false); xhr.open("POST", "Handler1.ashx"); xhr.send(fd); } function uploadComplete(evt) { alert(evt.target.responseText); } function uploadFailed(evt) { alert("There was an error attempting to upload the file."); } function uploadCanceled(evt) { alert("The upload has been canceled by the user or the browser dropped the connection."); } </script> </head> <body> <form id="form1" enctype="multipart/form-data" method="post" action="Handler1.ashx"> <input type="file" name="fileToUpload" id="fileToUpload"/> <input type="button" onclick="uploadFile()" value="Upload" /> </form> </body> </html>
and here is the ashx handler:
using System; using System.Collections.Generic; using System.Web.Extensions; using System.Linq; using System.Web; using System.Web.Services; using System.IO; namespace MultipleFileUploadTest { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { var stream = context.Request.InputStream; MemoryStream memoryStream; ReadFully(stream, out memoryStream); Byte[] ba = memoryStream.ToArray(); var path = @"C:\Users\giuseppe.JHP\Desktop\Image upload test\uploaded.gif"; using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)) { fs.Write(ba, 0, ba.Length); }