To handle file uploads with HttpListener
in C#, you need to parse the multipart form data and save the uploaded file. Here's an example that demonstrates the process:
using System; using System.IO; using System.Net; class Program { static void Main() { // Start the HttpListener HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); Console.WriteLine("Listening..."); // Handle incoming requests while (true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; // Check if the request is a POST and contains multipart/form-data if (request.HttpMethod == "POST" && request.ContentType.StartsWith("multipart/form-data")) { // Read the multipart form data var reader = new StreamReader(request.InputStream); var formData = reader.ReadToEnd(); // Parse the form data to retrieve the uploaded file var boundary = request.ContentType.Substring(request.ContentType.IndexOf("boundary=") + 9); var parts = formData.Split(new[] { "--" + boundary }, StringSplitOptions.RemoveEmptyEntries); foreach (var part in parts) { if (part.StartsWith("Content-Disposition: form-data") && part.Contains("filename=")) { var fileNameStart = part.IndexOf("filename=\"") + 10; var fileNameEnd = part.IndexOf("\"", fileNameStart); var fileName = part.Substring(fileNameStart, fileNameEnd - fileNameStart); var fileContentStart = part.IndexOf("\r\n\r\n") + 4; var fileContentEnd = part.LastIndexOf("\r\n"); var fileContent = part.Substring(fileContentStart, fileContentEnd - fileContentStart); // Save the uploaded file var filePath = Path.Combine(Path.GetTempPath(), fileName); File.WriteAllBytes(filePath, Convert.FromBase64String(fileContent)); Console.WriteLine($"File uploaded: {filePath}"); break; } } } // Send response string responseString = "File uploaded successfully!"; byte[] responseBytes = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentType = "text/plain"; response.ContentLength64 = responseBytes.Length; response.OutputStream.Write(responseBytes, 0, responseBytes.Length); response.Close(); } } }
In this example:
The HttpListener
is started and configured to listen on http://localhost:8080/
.
In the request handling loop, it checks if the request is a POST with multipart/form-data
content type.
It reads the entire request body, which contains the multipart form data.
The form data is parsed to extract the uploaded file's information, such as the filename and content.
The content of the uploaded file is base64 encoded in the example. You may adjust the parsing logic if your data is formatted differently.
The file is saved to a temporary location using File.WriteAllBytes
. Modify the file-saving logic to suit your requirements.
Finally, a response is sent back to the client to indicate a successful file upload.
Remember to handle exceptions, properly handle multipart boundaries, and perform necessary security validations before saving the uploaded file.
"C# HttpListener file upload example"
// Sample Code: HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; if (request.HasEntityBody) { using (Stream body = request.InputStream) { using (StreamReader reader = new StreamReader(body, request.ContentEncoding)) { string content = reader.ReadToEnd(); // Process the file content. } } }
"HttpListener file upload with multipart/form-data in C#"
multipart/form-data
content type commonly used in HTML forms.// Sample Code: HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; if (request.HasEntityBody && request.ContentType.StartsWith("multipart/form-data")) { // Parse multipart/form-data and extract file content. }
"C# HttpListener save uploaded file to disk"
// Sample Code: string savePath = "C:\\Uploads\\"; string fileName = Path.GetFileName(request.RawUrl); using (FileStream fs = new FileStream(Path.Combine(savePath, fileName), FileMode.Create)) { body.CopyTo(fs); }
"Handle large file uploads with HttpListener in C#"
// Sample Code: byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = body.Read(buffer, 0, buffer.Length)) > 0) { // Process the buffer. }
"C# HttpListener handle multiple file uploads"
// Sample Code: HttpListenerRequest request = context.Request; foreach (string key in request.QueryString.AllKeys) { if (request.Files.AllKeys.Contains(key)) { HttpPostedFile file = request.Files[key]; // Process each uploaded file. } }
"Secure HttpListener file uploads in C#"
// Sample Code: if (request.UrlReferrer != null && request.UrlReferrer.Host == "trusted-site.com") { // Process the file upload from the trusted source. }
"C# HttpListener handle file upload errors"
// Sample Code: try { // Process file upload. } catch (Exception ex) { // Handle the error. }
"C# HttpListener receive file upload progress"
// Sample Code: long totalBytes = request.ContentLength64; long bytesRead = 0; int chunkSize = 4096; while (bytesRead < totalBytes) { bytesRead += body.Read(buffer, 0, chunkSize); // Calculate and report upload progress. }
"HttpListener file upload authentication in C#"
// Sample Code: if (IsAuthenticated(request)) { // Process the authenticated file upload. }
"C# HttpListener CORS for file uploads"
// Sample Code: context.Response.AddHeader("Access-Control-Allow-Origin", "*"); // Process the file upload request.
django-guardian zurb-foundation-6 retain-cycle cross-validation location-provider count-unique touchpad flexible-array-member null-check redis-server