【问题标题】:Null parameter when trying to pass a blob to C# controller尝试将 blob 传递给 C# 控制器时为空参数
【发布时间】:2013-09-23 03:03:05
【问题描述】:

所以我指的是 Saving WAV File Recorded in Chrome to Server 将 blob 保存到我的服务器。但是,我无法将这个 PHP 语句翻译成 C#。

<?php
// get the temporary name that PHP gave to the uploaded file
$tmp_filename=$_FILES["that_random_filename.wav"]["tmp_name"];
// rename the temporary file (because PHP deletes the file as soon as it's done with it)
rename($tmp_filename,"/tmp/uploaded_audio.wav");
?>

这是我目前尝试过的

查看

var fd = new FormData();
fd.append("that_random_filename.wav", blob);
xhr.open("POST", "SubmitSound", true);
xhr.send(fd);

查看模型

public class SoundBlob
{        
    public string key { get; set; }
    public HttpPostedFileBase blob { get; set; } // I tried byte[] and string too
}

控制器

       [HttpPost]
        public ActionResult SubmitSound(SoundBlob blob)
        {
            // Create the new, empty data file.
            string fileName = AppDomain.CurrentDomain.BaseDirectory + "/Content/Sound/" + Environment.TickCount + ".wav";
            FileStream fs = new FileStream(fileName, FileMode.CreateNew);
            BinaryWriter w = new BinaryWriter(fs);

            blob.blob.SaveAs(blob.key);
            w.Close();
            fs.Close();           
            return new JsonResult() { Data = "Saved successfully" };
        }

keyblobSoundBlob 均为空!我该如何解决?

【问题讨论】:

    标签: c# javascript php asp.net-mvc


    【解决方案1】:

    不依赖于 C# 类型,而是使用此脚本。

                var length = Request.ContentLength;
                var bytes = new byte[length];
                Request.InputStream.Read(bytes, 0, length);
    

    【讨论】:

      【解决方案2】:

      试试这个:

      客户:

      <script src="http://code.jquery.com/jquery-1.10.2.min.js" ></script>
      <div class='wrapper' >
          <input type='file' class='target' id='targetinput' />
      </div>
      

      Javascript:

      var xhr = new XMLHttpRequest();
      var fd = new FormData();
      fd.append("blob.blob", document.getElementById('targetinput').files[0]);
      xhr.open("POST", "/Home/SubmitSound", true);
      xhr.send(fd);
      

      服务器:

      [HttpPost]
      public ActionResult SubmitSound(SoundBlob blob)
      {
              var fileName = Server.MapPath(string.Format("/Content/Sound/{0}.wav", Environment.TickCount));
              blob.blob.SaveAs(fileName);
              return new JsonResult { Data = "Saved successfully" };
      }
      

      完美的工作,我刚刚检查了它

      【讨论】:

      • 抱歉,我没有提供足够的背景信息。基本上,我使用 javascript 库来录制文件,录制完成后,blob 被传递给函数以将其保存到客户端计算机。如果查看webaudiodemos.appspot.com/AudioRecorder/index.html的源码,可以看到函数doneEncoding,这就是我要修改的。
      • 我想要实现的是用户可以点击一个按钮,录制他们的声音,然后再次点击同一个按钮,然后blob可以上传到数据库。恐怕您的解决方案需要人们选择一个文件。
      • 这是为我做的。干得好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      相关资源
      最近更新 更多