<div id="container">
<video autoplay="true" id="videoElement">
</video>
<canvas id="myCanvas" width="400" height="350"></canvas>
<button onclick="snapshot()">Click</button>
</div>
这里我通过 ajax 调用将 imgInfo
的值传递给我的 MVC Controller 。
<script>
var video = document.querySelector("#videoElement");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
});
}
function snapshot() {
// Draws current image from the video element into the canvas
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
var imgInfo = canvas.toDataURL("image/png");
console.log(imgInfo);
var image = imgInfo; // to create a image read the previous example
$.ajax({
url: "@Url.Action("Contact","Home")",
// send the base64 post parameter
data: {
base64: image
},
// important POST method !
type: "post",
complete: function () {
console.log("Ready");
}
});
}
</script>
我正在将此数据传递给联系 Controller ,它在 Convert.FromBase64String()
中给出了错误......
The input is not a valid Base64 string, as it contains a character that is not a base 64 character, more than two fill characters, or an invalid character among the fill characters
[HttpPost]
public ActionResult Contact(string base64)
{
var arr = Convert.FromBase64String(base64); //this line gives error.
Stream stream = new MemoryStream(arr);
}
字符串 Controller 正在接收
"data:image/png;base64,iVBsRq1Hm1dxzRO0XRdtB3rHjGO3o/DOOpZtoO+HM08RFvV0VRNVLzPtoqZ/aO7a7T20XYRsY1an8nzrKLvD2Kqxph1hxtdcx6nGOZe+1V7i7c09tFFHcsxotuOsYltnC8qFjDGaeZla3+NVR3TPOo9tXPEIqqYFpP2FHt6mip2bDQt73wbUfXRdry7Kpp5FXM96P2x1tzVPHVs0d2vqamjm3lGv3P2SsOJqrqodQ9TzBPntY2m64NtV0/siyqGRRt9XceyrWJZNXqeYaqimg9irhfas9M8xHo8jXqaoh11amIYNlG1c2yaMeppjGWz0M92bRf11EZbs15z9PMUw6JjU0RU51FNTVRTG3V1I4a5i7ZTqWCBQ0g6Sn0gNTwFtlDXz80k256S07YU/VP2nQ2b59+/kX78uuv2oOPkD+3NvPs5NAmCvW5oz9evmw///RjW67+USLEO2YfS4igIEhllfc+dZ5HApCJdRIlAlvaOKFMC1fWgKVzL/72pQ/XGZwKxcb/p6xEXROyvtqN2tR80bEeQPdH+dsugEwvY6NPufXDeHn38qD24P9fxkKn2P//6uy0WCzntkStJE5os58njJ+3i6dMASUVORK5CYII="
如何将此字符串转换为 base64
格式?
最佳答案
您可以通过从字符串中删除 data:image/png;base64,
来解决此问题,例如:
public ActionResult Contact(string base64)
{
if (base64.IndexOf(',') > 0)
{
base64 = base64.Substring(base64.IndexOf(',') + 1);
}
var arr = Convert.FromBase64String(base64);
Stream stream = new MemoryStream(arr);
}
关于javascript - 错误: The input is not a valid Base-64 string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61014041/