c#
C++进阶:掌握STL和模板,参考《C++ Primer》 #生活技巧# #工作学习技巧# #编程语言学习路径#
您不能使用StreamReader,因为它旨在读取字节在 UTF8 中的流。相反,您想将流的内容读取到接收缓冲区,删除所有不需要的内容,获取上传文件的文件扩展名,提取上传文件的内容,然后将文件内容保存到新文件。我在这篇文章中展示的代码假定您的表单如下所示:
<form enctype="multipart/form-data" method="POST" action="/uploader"> <input type="file" name="file"> <input type="submit"> </form>
如您所见,代码仅用于处理只有文件的表单。由于无法从 application/x-www-form-urlencoded 表单中提取服务器上文件的内容,因此您必须包含“multipart/form-data”。
首先,对于这种处理上传文件的方法,您首先需要这段代码:
using System; using System.IO; using System.Text; using System.Net; using System.Collections.Generic;
其次,您需要将 的内容读取request.InputStream到接收缓冲区或byte[]. 我们通过使用浏览器发送byte[]的标头长度创建一个缓冲区来做到这一点。Content-Length然后,我们读取request.InputStream缓冲区的内容。代码如下所示:
int len = int.Parse(request.Headers["Content-Length"]); byte[] buffer = new byte[len]; request.InputStream.Read(buffer, 0, len);
流看起来有点像这样:
------WebKitFormBoundary9lcB0OZVXSqZLbmv Content-Disposition: form-data; name="file"; filename="example-file.txt" Content-Type: text/plain file contents here ------WebKitFormBoundary9lcB0OZVXSqZLbmv--
接下来,您需要获取上传文件的文件扩展名。我们可以使用以下代码来做到这一点:
string fileExtension = Encoding.UTF8.GetString(bytes).Split("\r\n")[1].Split("filename=\"")[1].Replace("\"", "").Split('.')[^1];
然后,我们需要获取文件的内容。我们通过删除开头的内容(-----WebKitFormBoundary、Content-Disposition、Content-Type 和一个空白行)来做到这一点,然后删除请求正文的最后一行,加上一个额外\r\n的结尾。这是执行此操作的代码:
// note that the variable buffer is the byte[], and the variable bytes is the List<byte> string stringBuffer = Encoding.UTF8.GetString(buffer); List<byte> bytes = new List<byte>(buffer); string[] splitString = stringBuffer.Split('\n'); int lengthOfFourLines = splitString[0].Length + splitString[1].Length + splitString[2].Length + splitString[3].Length + 4; bytes.RemoveRange(0, lengthOfFourLines); int lengthOfLastLine = splitString[^2].Length+2; bytes.RemoveRange(bytes.Count - lengthOfLastLine, lengthOfLastLine); buffer = bytes.ToArray();
最后,我们需要将内容保存到文件中。下面的代码生成一个带有用户指定文件扩展名的随机文件名,并将文件内容保存到其中。
string fname = ""; string[] chars = "q w e r t y u i o p a s d f g h j k l z x c v b n m Q W E R T Y U I O P A S D F G H J K L Z X C V B N M 1 2 3 4 5 6 7 8 9 0".Split(" "); for (int i = 0; i < 10; i++) { fname += chars[new Random().Next(chars.Length)]; } fname += fileExtension; FileStream file = File.Create(fname); file.Write(buffer); file.Close();
这是放在一起的整个代码:
public static void Main() { var listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); while(true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; if(request.HttpMethod=="POST") SaveFile(request); response.OutputStream.Write(Encoding.UTF8.GetBytes("file successfully uploaded")); response.OutputStream.Close(); } } void SaveFile(HttpListenerRequest request) { int len = (int)request.ContentLength64; Console.WriteLine(len); byte[] buffer = new byte[len]; request.InputStream.Read(buffer, 0, len); string stringBuffer = Encoding.UTF8.GetString(buffer); Console.WriteLine(stringBuffer.Replace("\r\n","\\r\\n\n")); string fileExtension = stringBuffer.Split("\r\n")[1] .Split("filename=\"")[1] .Replace("\"", "") .Split('.')[^1] ; List<byte> bytes = new List<byte>(buffer); string[] splitString = stringBuffer.Split('\n'); int lengthOfFourLines = splitString[0].Length + splitString[1].Length + splitString[2].Length + splitString[3].Length + 4; bytes.RemoveRange(0, lengthOfFourLines); int lengthOfLastLine = splitString[^2].Length+2; bytes.RemoveRange(bytes.Count - lengthOfLastLine, lengthOfLastLine); buffer = bytes.ToArray(); string fname = ""; string[] chars = "q w e r t y u i o p a s d f g h j k l z x c v b n m Q W E R T Y U I O P A S D F G H J K L Z X C V B N M 1 2 3 4 5 6 7 8 9 0".Split(" "); for (int i = 0; i < 10; i++) { fname += chars[new Random().Next(chars.Length)]; } fname += "." + fileExtension; FileStream file = File.Create(fname); file.Write(buffer); file.Close(); }
此外,如果您想将上传的文件发送到客户端,这里有一个有用的功能,可以将文件发送到客户端。
// Make sure you are using System.IO, and System.Net when making this function. // Also make sure you set the content type of the response before calling this function. // fileName is the name of the file you want to send to the client, and output is the response.OutputStream. public static void SendFile(string fileName, Stream output) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); fs.CopyTo(output); fs.Close(); output.Close(); }
网址:c# https://klqsh.com/news/view/105203
相关内容
c哩c哩c哩c哩舞 c哩c哩 2018赤木狸 古早视频同福客栈的C位明星
16年前,大佬面前,刘亦菲就站C位,16年后还站C位,只有刘亦菲了
你们看C位也是风韵犹存?
叶童回应番位争议称发光即C位
练瑜伽时体育老师C了我一节课
David C. Theophilus
《男宝星球2》C组导师章昊今晚亮相
C罗谈到儿子马特奥最喜欢姆总:姆巴佩比你强!
“Triple C”亨利·塞胡多(Henry Cejudo)身穿哈萨克斯坦服装!