7

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

Adham
  • 63,550
  • 98
  • 229
  • 344
  • I think this is a valid question. If you're doing an IFRAME post to upload a file for IE<=9 that looks like AJAX, then you need to create an html form with a file in, and post to a .NET page. That's exactly what I'm trying to do. So the question then is, how does the ASPX page extract the file from the posted data. Which is what the question is asking. – Sean Jul 30 '14 at 21:10
  • 1
    I agree with @Sean... this IS a valid question... not sure why it was closed. – FastTrack Nov 19 '14 at 16:49
  • I've noticed that at times, questions are closed because they are not worded in the best English. Which is an absolutely stupid reason for which to close a question. If the content of the question is legitimate, should anything else matter? – Arvindh Mani Oct 25 '17 at 18:33

2 Answers2

23

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Can you please shoe me a full example, I am not expert in .NET. I have done with android client , and want to make the server side component ? – Adham Feb 25 '13 at 16:52
  • Sure, I have updated my answer with an example. – Darin Dimitrov Feb 25 '13 at 16:54
  • Thank you sir, does this works for it as client side ?http://stackoverflow.com/questions/1067655/how-to-upload-a-file-using-java-httpclient-library-working-with-php-strange-pr/1068132#1068132 – Adham Feb 25 '13 at 17:08
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

JoshBerke
  • 66,142
  • 25
  • 126
  • 164