7

I have the following form

<form id="upload" method="post" EncType="Multipart/Form-Data" action="reciver.aspx">
        <input type="file" id="upload" name="upload" /><br/>
        <input type="submit" id="save" class="button" value="Save" />            
</form>

When I look at the file collection it is empty.

HttpFileCollection Files = HttpContext.Current.Request.Files;

How do I read the uploaded file content without using ASP.NET server side control?

1
  • I am limited to .Net 2.0 Commented Sep 17, 2010 at 15:06

2 Answers 2

7

Why do you need to get the currect httpcontext, just use the page's one, look at this example:

//aspx
<form id="form1" runat="server" enctype="multipart/form-data">
 <input type="file" id="myFile" name="myFile" />
 <asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>

//c#
protected void btnUploadClick(object sender, EventArgs e)
{
    HttpPostedFile file = Request.Files["myFile"];
    if (file != null && file.ContentLength )
    {
        string fname = Path.GetFileName(file.FileName);
        file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
    }
}

The example code is from Uploading Files in ASP.net without using the FileUpload server control

Btw, you don't need to use a server side button control. You can add the above code to the page load where you check if the current state is a postback.

Good luck!

Sign up to request clarification or add additional context in comments.

Comments

1

Here is my final solution. Attaching the file to an email.

//Get the files submitted form object
            HttpFileCollection Files = HttpContext.Current.Request.Files;

            //Get the first file. There could be multiple if muti upload is supported
            string fileName = Files[0].FileName;

            //Some validation
            if(Files.Count == 1 && Files[0].ContentLength > 1 && !string.IsNullOrEmpty(fileName))
            { 
                //Get the input stream and file name and create the email attachment
                Attachment myAttachment = new Attachment(Files[0].InputStream, fileName);

                //Send email
                MailMessage msg = new MailMessage(new MailAddress("[email protected]", "name"), new MailAddress("[email protected]", "name"));
                msg.Subject = "Test";
                msg.Body = "Test";
                msg.IsBodyHtml = true;
                msg.Attachments.Add(myAttachment);

                SmtpClient client = new SmtpClient("smtp");
                client.Send(msg);
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.