我正在客户端表单上生成文本的动态图像,并希望将该img附加到mvc中的模型中。如何将img发送到附加到模型的动作控制器。
public class ReviewModel
{
public string Image { get; set; }
}
<div class="col-md-12">
<!-- Input HTML text is inside the DIV -->
<div id="talltweets" class="mySign">
The <b>quick brown fox</b> jumped over the <i>lazy dog</i>.
</div>
<!-- The PNG image will be added here -->
<div style="background:yellow;padding:10px">
<img id="textScreenshot" src="">
</div>
</div>
<!-- Include the HTMl2Canvas library -->
<script src="//cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script>
html2canvas(document.getElementById("talltweets"), {
onrendered: function (canvas) {
var screenshot = canvas.toDataURL("image/png");
document.getElementById("textScreenshot").setAttribute("src", screenshot);
}
});
</script>
答案 0 :(得分:0)
您可以将图像作为文件而不是文本发送。只需要一些js代码。 来自here的示例。
使用提交事件添加表单。
document.getElementById("mainForm").addEventListener("submit", function (event) {
event.preventDefault();
var XHR = new XMLHttpRequest();
var FD = new FormData();
var ImageURL = document.getElementById("textScreenshot").getAttribute("src");
var block = ImageURL.split(";");
var contentType = block[0].split(":")[1];
var realData = block[1].split(",")[1];
var blob = b64toBlob(realData, contentType);
FD.append('image', blob);
XHR.open('POST', '/api/values/imageExample');
XHR.send(FD);
});
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
将表单发布到服务器端,并根据需要处理收到的文件。这是.NetCore API控制器示例,它将请求文件保存到文件系统。
[Route("api/[controller]")]
public class ValuesController : Controller
{
[Route("imageExample")]
public IActionResult ImageExample()
{
if (Request.Form != null && Request.Form.Files.Any())
{
foreach (var formFile in Request.Form.Files)
{
var filePath = Path.Combine("c:\\temp\\", formFile.FileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
formFile.CopyTo(fileStream); //saving file to file system
}
}
}
return Redirect("/somewhere-else");
}
}