C# 如何在 .NET 中将 POST 请求内容保存为文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15072040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save a POST request content as a file in .NET
提问by Adham
I have a client application that makes a POST
request to asp.net URL
( it is used to uplaod a file to .NET
).
我有一个客户端应用程序, 它POST
向asp.net URL
(它用于将文件上传到.NET
)。
How to make asp.net page receives this request and save it as a file ?
如何让asp.net 页面接收到这个请求并将其保存为文件?
@ Darin Dimitrov
I have tried your code, but I got 500 internal server error
how can I track it ?!
@ Darin Dimitrov 我试过你的代码,但我500 internal server error
知道如何跟踪它?!
回答by Darin Dimitrov
If the client uses multipart/form-data
request encoding (which is the standard for uploading files) you could retrieve the uploaded file from the Request.Files
collection. For example:
如果客户端使用multipart/form-data
请求编码(这是上传文件的标准),您可以从Request.Files
集合中检索上传的文件。例如:
protected void Page_Load(object sender, EventArgs e)
{
foreach (HttpPostedFile file in Request.Files)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
or if you know the name used by the client you could directly access it:
或者,如果您知道客户端使用的名称,则可以直接访问它:
HttpPostedFile file = Request.Files["file"];
If on the other hand the client doesn't use a standard encoding for the request you might need to read the file from the Request.InputStream
.
另一方面,如果客户端没有对请求使用标准编码,则您可能需要从Request.InputStream
.
回答by JoshBerke
You can also save the entire request using
您还可以使用保存整个请求
HttpContext.Current.Request.SaveAs(filename,includeHeaders)
Assuming the data is not being uploaded as multipart/form-data
假设数据没有作为 multipart/form-data 上传