Post JSON with data AND file to Web Api - jQuery / MVC

前端 未结 1 694
暗喜
暗喜 2020-12-24 12:20

I need to post to an Api Controller w/ JSON (preferably) with ONE request.

The issue is passing data AND a file (image uploaded). My property is coming up empty (nul

相关标签:
1条回答
  • 2020-12-24 12:54

    You can't upload a file(that is arbitrary binary data) with JSON as JSON is a text format. you'll have to use multipart form data.

    // create model for controller
    var model = new FormData();
    model.append('Name', $.trim($contestForm.find('[name="nombre"]').val()) + ' ' + $.trim($contestForm.find('[name="apellido"]').val()));
    model.append('Email', $.trim($contestForm.find('[name="email"]').val().toLowerCase()));
    model.append('City', $.trim($contestForm.find('[name="cuidad"]').val()));
    model.append('Title', $.trim($contestForm.find('[name="title"]').val()));
    model.append('Description', $.trim($contestForm.find('[name="description"]').val()));
    model.append('CountryCode', 'co');
    model.append('Image', $contestForm.find('[name="file-es"]')[0].files[0]);  // this has the file for sure
    
    $.ajax({
        url: '/Umbraco/api/ControllerName/CreateContestEntry',
        type: 'POST',
        dataType: 'json',
        data: model,
        processData: false,
        contentType: false,// not json
        complete: function (data) {
            var mediaId = $.parseJSON(data.responseText); //?
    
        },
        error: function (response) {
            console.log(response.responseText);
        }
    });
    
    0 讨论(0)
提交回复
热议问题