【问题标题】:Ajax and MVC 5 - Upload image binary by ajaxAjax 和 MVC 5 - 通过 ajax 上传图像二进制文件
【发布时间】:2014-09-16 16:00:55
【问题描述】:

我正在使用 knockoutjs 和 mvc5 编写代码,其中在 ui 上选择图像并通过 ajax 上传图像的二进制文件。

我无法真正展示有关图片上传的太多内容,但我知道它有效。图片是浏览器本地的,二进制文件存储在视图模型中。

问题是将此二进制文件上传到 mvc。

在我的 javascript 中,我正在使用以下内容构建帖子:

var customerData = {
    CustomerName: self.CustomerName(),
    CustomerImage: self.CustomerImage().imageBinary(),
    CustomerJobNumber: self.CustomerJobNumber()
};
//If add, enable remaining area, change id, and start customer edit
if (window.location.hash == "#customer-add") {
    $.ajax({
        type: 'POST',
        url: "/Customer/SaveNew",
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(customerData),
        success: function(data) {
            /*CODE*/
            var title = data.title;
            var msg = data.message;
            if (data.success == 0) {
                //growl as to why
            } else {
                //growl success
                window.location.hash = "#customer-edit-" + data.newCustomer.CustomerId;
                self.SetCustomerFields(data.newCustomer);
                self.LoadCustomers();
            }
        },
        error: function(err) {
            alert(err);
            //growl
        }
    });
}

在我的控制器中我有:

    public class NewCustomerData
    {
        public string CustomerName { get; set; }
        public byte[] CustomerImage { get; set; }
        public string CustomerJobNumber { get; set; }
    }

    [HttpPost]
    public ActionResult SaveNew(NewCustomerData data)
    {
          //Does stuff
    }

当我闯入正在运行的 javascript 时,我发送的 CustomerImage 对象属于 ArrayBuffer 类型。如果我将它转换为 Uint8Array,我可以验证是否有内容。但二进制文件从未出现在控制器中。

我没有分配正确的 c# 对象吗?

【问题讨论】:

  • 也请发表您的看法
  • 视图是否必要?我遇到的问题是使用 ajax 将 ArrayBuffer 发布到控制器。我在 ajax 调用之前有数据,但它在 ajax 调用和被控制器方法拾取之间的某个地方消失了。
  • 您是否检查过浏览器上的网络选项卡以验证正确的数据是否正在影响服务器?通常我会在模型中使用 HttpPostedFileBase 而不是 byte[]
  • 我想问题出在内容类型上。您的 JSON.stringify(customerData) 显示什么?我想这样做的正确方法是像您一样将您的 CustomerImage 对象转换为 Uint8Array,然后发送到服务器。

标签: jquery asp.net-mvc knockout.js


【解决方案1】:

我对此的解决方案是将 JavaScript 中的 ArrayBuffer 转换为 Base-64 编码的字符串。然后我修改了服务器端的对象以接受一个字符串,瞧。

【讨论】:

  • 如果您使用的是 FileReader,您可以将其读取为 dataURL,将其与其他一些数据一起编码为 base64,然后使用方法here 对其进行解码。看来 btoa 在将数据转换为 base64 时有一些特殊性。
猜你喜欢
  • 2015-11-28
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 1970-01-01
  • 2015-06-16
  • 2021-12-10
相关资源
最近更新 更多