Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a POST request content as a file in .NET [closed]

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 ?!

like image 681
Adham Avatar asked Feb 25 '13 16:02

Adham


People also ask

Can we send a file in post request?

You can send files and binary data directly to Media Server using a POST request. One possible way to send a POST request over a socket to Media Server is using the cURL command-line tool.

What is HttpPostedFileBase in MVC?

The HttpPostedFileBase class is an abstract class that contains the same members as the HttpPostedFile class. The HttpPostedFileBase class lets you create derived classes that are like the HttpPostedFile class, but that you can customize and that work outside the ASP.NET pipeline.


2 Answers

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.

like image 72
Darin Dimitrov Avatar answered Sep 20 '22 18:09

Darin Dimitrov


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

like image 43
JoshBerke Avatar answered Sep 19 '22 18:09

JoshBerke