尝试将blob传递给C#控制器时的空参数

时间:2013-09-23 03:03:06

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

所以我指的是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" };
        }

key的{​​{1}}和blob都为空!我该如何解决?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

试试这个:

<强>客户端:

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

完美无缺,我刚检查过