Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically upload file after file has been chosen

I have the following code for uploading a file in my site:

@using (Html.BeginForm("UploadProfileImage", "Member", FormMethod.Post, new { @encType = "multipart/form-data" }))
   {

     @Microsoft.Web.Helpers.FileUpload.GetHtml(initialNumberOfFiles: 1, includeFormTag: false, uploadText: "Upload File",allowMoreFilesToBeAdded:false)
    <span class="success">@ViewData["SuccessMessage"]</span>
     <input class="button" type="submit" name="submit" value="Upload" />         

}

I want this to be able to automatically post after the user selects the file from the "browse" button. Currently, the user has to click upload every time the user chooses a file to upload, anyway to make this process automatic?

like image 208
anthonypliu Avatar asked Oct 20 '12 19:10

anthonypliu


2 Answers

The file upload control supports onchange event. Hope that can be used to trigger the upload

<form name="upload" action="uploadfile.aspx" method="POST">
    <input name="myfile" type="file" onchange="UploadFile()" />
</form>

<script>
   function UploadFile()
   {
      //do validation here
      document.forms['upload'].submit();
   }
</script>
like image 184
codingbiz Avatar answered Oct 19 '22 22:10

codingbiz


ASP:

<input type="file" onchange="this.form.submit();" name="fUpload"/>

CodeBehind:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        System.Web.HttpPostedFile file = Request.Files["fUpload"];
        if (file != null && file.ContentLength > 0)
        {
            file.SaveAs(@"C:\dir\"+System.IO.Path.GetFileName(file.FileName));
        }
    }

}

asp:FileUpload instead of input:

ASP:

<asp:FileUpload runat="server" onchange="this.form.submit();" ID="fuFile"/>

Codebehind:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (fuFile.PostedFile.FileName != string.Empty  && fuFile.PostedFile.ContentLength > 0)
        {
            fuFile.PostedFile.SaveAs(@"C:\dir\" + fuFile.FileName);
        }
    }

}
like image 40
fubo Avatar answered Oct 19 '22 23:10

fubo