MVC Progress Bar using http Post

StantonR picture StantonR · Feb 14, 2011 · Viewed 8.1k times · Source

I am using Microsoft MVC I have written a view that uploads files to the Amazon S3 API. I would like a progress bar in my view to show the progress of the processing of that action in my controller not the uploading of the file in particular.

I have tried a few JQUERY/AJAX uploaders but every time I loose the value of The HttpPostedFileBase and the value of the file is null.

I basically need to find a progress bar function that supports Post and multipart/form-data.

Code is below

ASPX

<%using (Html.BeginForm("Upload", "Tracks", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
  <label for="BandName">Artist</label> 
       <%=Html.TextBox("Artists") %><%:Html.ValidationMessage("Artist","*")%>
        <div class="clearfix">
        </div>
        <label for="SongName">Song Title
        </label>
          <%=Html.TextBox("SongName") %><%:Html.ValidationMessage("SongName","*")%>
        <div class="clearfix">
        </div>
         <label for="SongName">Genre(s)
        </label>
          <%=Html.TextBox("Genres") %><%:Html.ValidationMessage("Genres","*")%>
        <div class="clearfix">
        </div>
        <label for="SongName">Mood(s)
        </label>
          <%=Html.TextBox("Moods") %><%:Html.ValidationMessage("Moods","*")%>
        <div class="clearfix">
        </div>

        <%:Html.Label("Country") %><%=Html.DropDownListFor(x => x.OrigCountryOptions,Model.OrigCountryOptions)%> <br /><br />
          <div class="clearfix">
        </div>
        <label for="FileName">File
        </label>
         <input type="file" name="SongFile" id="SongFile"/>
        <div class="clearfix">
        </div>


        <input type="submit" value="Submit" />
<%
   }
   %>

Controller action

  [Authorize]   
  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult Upload(Track track, Guid origcountryoptions, HttpPostedFileBase SongFile)
    {

        DateTime timestamp = DateTime.Now;
        EncryptManager _encryptManager = new EncryptManager();
        EmailService _emailService ;

        string strMySignature = _encryptManager.GetSignature(
               cAWSSecretKey,
               "PutObjectInline",
               timestamp);

        AmazonS3 amazonS3 = new AmazonS3();

        string filename = SongFile.FileName;

        int FileLen = SongFile.ContentLength;
        byte[] buf = new byte[SongFile.ContentLength];
        int data = SongFile.InputStream.Read(buf, 0, FileLen);



        if (FileLen > 100000000)
            ModelState.AddModelError("LargeFile", "File Size is limited to 10mb");
        if (filename.Substring(filename.Length - 3, 3).ToUpper() !=  "MP3")
            ModelState.AddModelError("FileFormat", "Upload is limited to MP3's");
        if (String.IsNullOrEmpty(track.Artists))
            ModelState.AddModelError("Artist", "Please enter the artist name.");
        if (String.IsNullOrEmpty(track.Genres))
            ModelState.AddModelError("Genres", "Please enter the Genre(s).");
        if (String.IsNullOrEmpty(track.Moods))
            ModelState.AddModelError("Moods", "Please enter the Moods(s).");
        if (String.IsNullOrEmpty(track.Songname))
            ModelState.AddModelError("SongName", "Please enter the Song Name.");

        MetadataEntry[] metadata = new MetadataEntry[2];
        metadata[0] = new MetadataEntry();
        metadata[0].Name = "Content-Type";
        metadata[0].Value = SongFile.ContentType;
        metadata[1] = new MetadataEntry();
        metadata[1].Name = "filename";
        metadata[1].Value = filename;

        PutObjectResult result = amazonS3.PutObjectInline("PayForPlay.Tracks",
                                     cAWSSecretKey, metadata, buf,
                                     SongFile.ContentLength, null, StorageClass.STANDARD,
                                     true, cAWSAccessKeyId, timestamp,
                                     true, strMySignature, null);



        if (ModelState.IsValid)
        {


            using (var scopaddTrack = new UnitOfWorkScope())
            {
                var person = _personService.GetPerson(SessionWrapper.PersonId);

                Country origCountry = _lookupService.GetCountry(origcountryoptions);
                var newtrack = _trackService.CreateTrack(person, origCountry, track.Artists,
                                                         track.Moods, track.Genres, track.Songname);
                scopaddTrack.Commit();

                try
                {

                    var defaultClient = new DefaultEmailClient(ConfigurationManager.AppSettings["SMTPServer"],
                        ConfigurationManager.AppSettings["SMTPUsername"],
                        ConfigurationManager.AppSettings["SMTPPassword"]);
                    var service = new EmailService(defaultClient);

                    var email = new Email
                                    {
                                        ToAddress = ConfigurationManager.AppSettings["ToAddress"],
                                        ToName = ConfigurationManager.AppSettings["ToAddress"],
                                        FromAddress = ConfigurationManager.AppSettings["FromAddrress"],
                                        FromName = ConfigurationManager.AppSettings["FromAddrress"],
                                        Subject = "New Track Added",
                                        Body = "<html><body><h1>Wesbank Email Service Working</h1></body></html>",
                                        IsHtml = true
                                    };
                    service.SendEmail(email);

                    email.Subject = "Wesbank Email Service - Async Sorted";
                    service.SendAsycnEmail(email);

                }
                catch (Exception exception)
                {
                }

            }






            return RedirectToAction("List");
        }
        else
        {
            var countryoptions = _lookupService.GetAllCountries();
            var tracklist = _trackService.GetAllTracksByPerson(SessionWrapper.PersonId);
            var viewmodel = new TracksViewModel(tracklist, countryoptions);
            return View("Add", viewmodel);
        }


    }

Answer

Brandon Joyce picture Brandon Joyce · Feb 15, 2011

Here is an example that I think will help you: Asynchronous Process With Progress Bar