我正在执行以下操作来上传.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();
}
答案 0 :(得分:0)
我认为这是因为您将其作为MIME类型" text / html"发送,而不是正确的类型" application / vnd.openxmlformats-officedocument.presentationml .presentation"
答案 1 :(得分:0)
我现在没有时间对此进行测试,但请尝试以下方法:
public static void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
using (var out = File.OpenWrite("output.pptx"))
{
request.InputStream.CopyTo(out);
}
response.StatusCode = 200;
response.ContentType = "text/html";
using (StreamWriter writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF8))
writer.WriteLine("File Uploaded");
response.Close();
}