Posting an object and a file in the same call to the server with jQuery.ajax

你。 提交于 2019-12-01 10:05:17

问题


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

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

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

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

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.


回答1:


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

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


来源:https://stackoverflow.com/questions/12101028/posting-an-object-and-a-file-in-the-same-call-to-the-server-with-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!