在ASP.Net MVC中使用sendAsBinary

vdh*_*ant 0 javascript asp.net-mvc image-uploading asp.net-mvc-3

我正在尝试使用以下内容允许用户将照片拖到页面上并上传这些照片。

http://alex-tech-adventures.com/development/x-html--css--javascript/97-drag-and-drop-upload-using-html5-with-firefox.html

现在,我一直在尝试使它的模型绑定起作用,但是到目前为止,内置的东西还算不上什么。有人知道我如何使它起作用吗???

作为备份,我知道我使用InputStream将发送的数据作为字符串拉出,然后将其序列化到我的对象中...

var stream = this.Request.InputStream;
var result = "";
using (var reader = new StreamReader(stream))
{
    result = reader.ReadToEnd();
}
var serializer = new JavaScriptSerializer(); 
var typedObjectResult = serializer.Deserialize<UploadInput>(result);
Run Code Online (Sandbox Code Playgroud)

但是我已经将消息的图像部分转换为字节数组,然后将其保存到文件中。图像的字符串内容如下所示。

data:image/jpeg;base64,/9j/4RjhRXhpZg........3Xuve9de6//9k=
Run Code Online (Sandbox Code Playgroud)

如何将其另存为图像?我是否应该能够将字节数组写入文件?

但是我主要关心的是正确绑定模型。

干杯

Dar*_*rov 5

好,让我们付诸行动。与往常一样,首先定义视图模型:

public class ImageData
{
    public string Description { get; set; }
    public string Filename { get; set; }
    public string Image { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后是一个控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<ImageData> images)
    {
        foreach (var item in images ?? Enumerable.Empty<ImageData>())
        {
            var tokens = item.Image.Split(',');
            if (tokens.Length > 1)
            {
                var buffer = Convert.FromBase64String(tokens[1]);
                var file = Path.Combine(HttpContext.Server.MapPath("~/"), item.Filename);
                System.IO.File.WriteAllBytes(file, buffer);
            }
        }
        return Json(new { Status = "OK" });
    }
}
Run Code Online (Sandbox Code Playgroud)

最后是一个视图:

<div id="uploadArea" style="background-color: yellow; width: 170px; height: 50px;">
    drop images here
</div>

@Html.ActionLink("Upload images", "index", null, new { id = "upload" })
<div id="imagesContainer" />


<script type="text/javascript">
    $('#uploadArea').bind('dragover', function (event) {
        event.preventDefault();
    }).bind('drop', function (event) {
        event.preventDefault();
        var files = event.originalEvent.dataTransfer.files;
        $.each(files, function (index, file) {
            var img = $('<img/>')
                .addClass('droppedImage')
                .attr('data-filename', file.name);
            $('#imagesContainer').append(img);
            img.file = file;
            var reader = new FileReader();
            reader.onloadend = function () {
                img.attr('src', reader.result);
            }
            reader.readAsDataURL(file);
        });
    });

    $('#upload').click(function () {
        var imagesJson = $('.droppedImage').map(function () {
            var $this = $(this);
            return {
                image: $this.attr('src'),
                filename: $this.attr('data-filename')
            };
        }).toArray();

        $.ajax({
            url: this.href,
            type: 'POST',
            data: JSON.stringify({ images: imagesJson }),
            contentType: 'application/json',
            success: function (result) {
                alert('success');
            }
        });
        return false;
    });
</script>
Run Code Online (Sandbox Code Playgroud)

现在启动您的HTML 5兼容浏览器并玩得开心。