使用jQuery.ajax在同一调用中将对象和文件发布到服务器 [英] Posting an object and a file in the same call to the server with jQuery.ajax

查看:141
本文介绍了使用jQuery.ajax在同一调用中将对象和文件发布到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在客户端发布以下MVC操作方法:

I'm trying to make a client side post to the following MVC action method:

[HttpPost]
public void Create(ProductModel product, HttpPostedFileBase imageFile)
{
    productServices.AddProduct(product, imageFile);
}

使用type ="submit"按钮很简单,但是在我的特殊情况下,我需要使用ajax调用来完成它.

This is straightforward with a type="submit" button, however in my particular case I need to do it with an ajax call.

我可以轻松地将ProductModel作为JSON传递.

I can just pass the ProductModel as JSON easy enough.

$.ajax({
    url: '/Product/Create',
    type: 'POST',
    data: JSON.stringify({product: {
            Id: 1,
            Name: "SomeName"
        }
    }),
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert("Product Created!");
    }
});

我还可以将文件作为FormData传递

I can also pass the file as FormData

var imageFileData = new FormData();
imageFileData.append('imageFile', myFileObject);

$.ajax({
    url: '/Product/Create',
    data: imageFileData,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        alert(data);
    }
});

但是,由于它们本质上是不同的contentTypes,我似乎无法在同一调用中将这2个单独的参数组合在一起.

However I can't seem to combine the 2 as separate parameters in the same call as they are fundamentally different contentTypes.

这可能吗?我会以错误的方式处理吗?任何帮助将不胜感激.

Is this possible? Am I going about this the wrong way? Any help would be appreciated.

推荐答案

您可以像添加文件一样将json添加到FormData中

You can add the json to the FormData just like you add the file

var imageFileData = new FormData();
imageFileData.append('imageFile', myFileObject);
imageFileData.append('product', JSON.stringify({product: {
            Id: 1,
            Name: "SomeName"
        });

$.ajax({
    url: '/Product/Create',
    data: imageFileData,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        alert(data);
    }
});

您可以将表单本身添加到FormData

of you can add the form itself to FormData

$.ajax({
    url: '/Product/Create',
    data: new FormData(theFormElement),
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        alert(data);
    }
});

这篇关于使用jQuery.ajax在同一调用中将对象和文件发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆