如何将POST请求内容保存为.NET中的文件

时间:2021-12-30 09:55:02

I have a client application that makes a POST request to asp.net URL( it is used to uplaod a file to .NET).

我有一个客户端应用程序向asp.net URL发出POST请求(它用于将文件上传到.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个内部服务器错误如何跟踪它?

2 个解决方案

#1


20  

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中读取文件。

#2


4  

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上传

#1


20  

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中读取文件。

#2


4  

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上传