我正在执行以下操作以上传 .pptx 文件并将其保存在服务器的磁盘上。
当我尝试打开文件时,它说它已损坏,无法打开。
这是因为我的编码类型还是其他原因?
是否可以在 POST 中将任何任意文件作为二进制文件发送并使其一次性到达服务器?
public static void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
StreamReader reader = new StreamReader(request.InputStream);
var res = reader.ReadToEnd();
reader.Close();
toLog.Add(res);
NameValueCollection coll = HttpUtility.ParseQueryString(res);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(res);
File.WriteAllBytes("output.pptx", bytes);
response.StatusCode = 200;
response.ContentType = "text/html";
using (StreamWriter writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF8))
writer.WriteLine("File Uploaded");
response.Close();
}
这是我发送的邮递员预览:
POST HTTP/1.1
Host: localhost:80
Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation
Cache-Control: no-cache
Postman-Token: 9a04aa33-cd44-d238-6873-b330524f4ae5
undefined
如果我在 np++ 中打开源(非损坏)文件,我会看到编辑器选择在 ANSI 中对其进行编码。
我目前正在用 UTF8 对其进行编码,而且我似乎没有用 ANSI 编码的选项。
此外,在比较文件大小时,我丢失了一千字节的数据。
编辑:我当前的代码现在是这个
这会将一个空文件写入磁盘。
public static void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
StreamReader reader = new StreamReader(request.InputStream);
var res = reader.ReadToEnd();
reader.Close();
Console.WriteLine(res);
NameValueCollection coll = HttpUtility.ParseQueryString(res);
using (var outp = File.OpenWrite("output.pptx"))
{
request.InputStream.CopyTo(outp);
}
response.StatusCode = 200;
response.ContentType = "text/html";
using (StreamWriter writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF7))
writer.WriteLine("File Uploaded");
response.Close();
}