使用 http Post 的 MVC 进度条

发布于 2024-10-17 15:25:10 字数 6299 浏览 5 评论 0原文

我正在使用 Microsoft MVC,我编写了一个将文件上传到 Amazon S3 API 的视图。 我希望在我的视图中显示一个进度条来显示控制器中该操作的处理进度,而不是特别是文件的上传。

我尝试了一些 JQUERY/AJAX 上传器,但每次我都会丢失 HttpPostedFileBase 的值并且文件的值为空。

我基本上需要找到一个支持Post和multipart/form-data的进度条功能。

代码位于

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" />
<%
   }
   %>

控制器操作下方

  [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);
        }


    }

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);
        }


    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲欢浪云 2024-10-24 15:25:10

这是一个我认为会对您有所帮助的示例: 带进度条的异步进程

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文