将 sendAsBinary 与 ASP.Net MVC 结合使用

发布于 2024-10-17 08:38:42 字数 957 浏览 0 评论 0原文

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

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

现在我一直在尝试让模型绑定工作,但到目前为止还没有内置任何东西。有谁知道我如何才能让它工作???

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

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);

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

data:image/jpeg;base64,/9j/4RjhRXhpZg........3Xuve9de6//9k=

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

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

干杯

I'm trying to use the following to allow a user to drag photos onto a page and have those photos uploaded.

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

Now I've been trying to get the model binding working of this but thus far haven't had much luck with anything built in. Does anyone know how I could get this to work???

As a backup, I know I use the InputStream to pull the sent data out as a string and then sdserialize into my object...

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);

But I'm having converting the image part of the message into a byte array and then saving that off to a file. The string content of the image looks like this.

data:image/jpeg;base64,/9j/4RjhRXhpZg........3Xuve9de6//9k=

How do I save this as an image? Should I just be able to write the byte array to a file?

But my main concern is getting the model binding right.

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南七夏 2024-10-24 08:38:42

好的,让我们将其付诸行动。一如既往,首先定义视图模型:

public class ImageData
{
    public string Description { get; set; }
    public string Filename { get; set; }
    public string Image { get; set; }
}

然后是控制器:

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

最后是视图:

<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>

现在启动您的 HTML 5 兼容浏览器并享受乐趣。

OK, let's put this into action. As always start by defining a view model:

public class ImageData
{
    public string Description { get; set; }
    public string Filename { get; set; }
    public string Image { get; set; }
}

then a controller:

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

and finally a view:

<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>

Now fire up your HTML 5 compliant browser and have fun.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文