I have a Webform(aspx) page.

In it we basically have this form that we "post" when pressing a button, but in reality it is not a true httpPOST, it is actually just a postback onclick event on that button. Within that event we get all information we want like what the user has typed in the textfields and so on. Which by the way works great.

But now I want to add a file uploader, more specifically an image uploader.

Can I grab the file the user has uploaded to the input type file from codebehind within a button event click postback? not a httppost.

有帮助吗?

解决方案

There is a specific control for this, FileUpload. Just add it on the page and you can get the uploaded file from this control on postback, quite similar to the other controls on page, like textboxes etc. for more info: http://asp.net-tutorials.com/controls/file-upload-control/

aspx page:

<form id="form1" runat="server">
    <asp:FileUpload id="FileUploadControl" runat="server" />
    <asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" />
    <br /><br />
    <asp:Label runat="server" id="StatusLabel" text="Upload status: " />
</form>

Code Behind:

protected void UploadButton_Click(object sender, EventArgs e)
{
    if(FileUploadControl.HasFile)
    {
        try
        {
            string filename = Path.GetFileName(FileUploadControl.FileName);
            FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
            StatusLabel.Text = "Upload status: File uploaded!";
        }
        catch(Exception ex)
        {
            StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

其他提示

Try this way:

<form id="frmUpload" enctype="multipart/form-data" runat="server" >
 <input type="file" id="FilesToUpload" name="FilesToUpload" />
 <asp:Button ID="UploadFiles" OnClick="ClickUpload" Text="Upload File . . ." runat="server"/>
</form>

and in code part:

protected void ClickUpload(object sender, EventArgs e)
{
    String fileToUpload = Request.Files["FilesToUpload"];

    //check file if exists for submitted
    if (fileToUpload != null && fileToUpload.ContentLength > 0)
    {
        string FileName = Path.GetFileName(fileToUpload.FileName);
        fileToUpload.SaveAs(Server.MapPath(Path.Combine("~/YourFileFolder/", FileName)));
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top