skdeveloper
skdeveloper

Reputation: 107

How to use HTML input control to upload files

I had HTML input control to upload file but the file returns empty.

<input type="file" class="upload"  runat="server" id="FUFile"/>

string tempVar = "~/res/Posts/" + FUFile.Value.ToString();
        FUFile.ResolveUrl(Server.MapPath(tempVar));

Upvotes: 4

Views: 15378

Answers (2)

MPelletier
MPelletier

Reputation: 16709

Just use a FileUpload control

<asp:FileUpload runat="server" ID="FUFile">
<asp:Button runat="server" ID="UploadButton" Text="Upload file" OnClick="UploadButton_Click"/>

You can then use FUFile's properties (FileContent for a stream, FileBytes for the full content as an array of bytes, PostedFile for the HttpPostedFile object which has the SaveAs method) as you need.

For example, see this answer for saving the stream: How do I save a stream to a file in C#?

See a full example at http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload(v=vs.110).aspx

Upvotes: 1

afzalulh
afzalulh

Reputation: 7943

The file is posting from the fileupload properly. If you need to save the FUFile.PostedFile :

if (FUFile.PostedFile != null)
{
    string tempVar = "~/res/Posts/" + FUFile.Value.ToString();
    FUFile.PostedFile.SaveAs(Server.MapPath(tempVar));
}

Here's how you can test it:

In markup I have this:

<input type="file" class="upload"  runat="server" id="FUFile"/>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

In code I have this method:

protected void Button1_Click(object sender, EventArgs e)
{
    if (FUFile.PostedFile != null)
    {
        string tempVar = "~/res/Posts/" + FUFile.Value.ToString();
        FUFile.PostedFile.SaveAs(Server.MapPath(tempVar));
    }
}

When I select a file and click the button, it uploads the file to ../res/Posts folder.

enter image description here

Upvotes: 1

Related Questions