How to save a POST request content as a file in .N

2019-03-28 12:15发布

问题:

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

How to make asp.net page receives this request and save it as a file ?

@ Darin Dimitrov I have tried your code, but I got 500 internal server error how can I track it ?!

回答1:

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:

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.



回答2:

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