邮政JSON数据和文件的Web API - jQuery的/ MVC [英] Post JSON with data AND file to Web Api - jQuery / MVC

查看:109
本文介绍了邮政JSON数据和文件的Web API - jQuery的/ MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要发布一个API控制器瓦特/ JSON(preferably)有一个请求。这是因为我使用一把umbraco 的路上我一直在做它,。我知道你可以使用SurfaceControllers,但我需要做一个非回发,因为我需要一把umbraco的TemplatePage模式不能使用自定义模式。

我开放的建议。

问题正在通过数据和文件(影像上载)。我以前从来没有做到这一点,和我的财产就要到了空(NULL)。

我看了相当多的博客,但似乎无法获得通过图像数据。

 公共类SomeModel
{
    公共字符串名称{;组; }
    公共字符串电子邮件{获得;组; }
    公共字符串城{搞定;组; }
    公共HttpPostedFileBase图片{搞定;组; }
    公共字符串名称{搞定;组; }
    公共字符串描述{搞定;组; }
    公共字符串国家code {搞定;组; }
}
    [HttpPost]
    公共无效CreateContestEntry(SomeModelmodel)
    {
        // model.Image总是空
        // ..获得的形象在这里 - 其他性能没有问题
    }

jQuery的

  //创建控制器模型
    VAR模型= {
        名称:$ .trim($ contestForm.find('[NAME =农布雷])VAL())+''+ $ .trim($ contestForm.find('[NAME =apellido]')。 VAL()),
        电子邮件:$ .trim($ contestForm.find('[NAME =电子邮件]')VAL()与toLowerCase()。)
        城市:$ .trim($ contestForm.find('[NAME =cuidad])VAL()),
        标题:$ .trim($ contestForm.find('[NAME =称号])VAL()。)
        说明:$ .trim($ contestForm.find('[NAME =说明]')VAL()。)
        国家code:CO,
        图片:$ contestForm.find('[NAME =文件-ES]')[0] .files [0] //这对于确保该文件
    };    $阿贾克斯({
        网址:'/一把umbraco / API / ControllerName / CreateContestEntry',
        输入:POST,
        数据类型:JSON,
        数据:JSON.stringify(模型),
        //数据:$('#测试表)序列化()//尝试这样做,用FORMDATA()
        过程数据:假的,
        异步:假的,
        的contentType:应用/ JSON的;字符集= UTF-8,
        完成:功能(数据){        },
        错误:功能(响应){
            的console.log(response.responseText);
        }
    });

博客我看了:


当我尝试了 FORMDATA $('#Form1的')。序列化()的办法,我的 provider.FileData provider.FormData 总是空的为好。我从方法删除模式参数和断点击中了,当我打开它。

  [HttpPost]
    公共无效CreateContestEntry()
    {
        串根= HttpContext.Current.Server.MapPath(〜/ App_Data文件);
        VAR提供商=新MultipartFormDataStreamProvider(根);        尝试
        {
            //读取表单数据。
            Request.Content.ReadAsMultipartAsync(供应商);            //这说明如何获取文件名。
            的foreach(在provider.FileData MultipartFileData文件)
            {
                //空
            }            的foreach(在provider.FormData.AllKeys VAR键)
            {
                的foreach(在provider.FormData.GetValues​​ VAR VAL(键))
                {
                    //空
                }
            }
            //返回Request.CreateResponse(的HTTPStatus code.OK);
        }
        赶上(异常前)
        {        }
    }


解决方案:

去了@穆萨的回答,这里的API控制器code。我映射的NameValueCollection到我的模型。

  [HttpPost]
    公共无效CreateContestEntry()
    {
        尝试
        {
            //获取第一变量
            NameValueCollection中雷士= HttpContext.Current.Request.Form;
            VAR模型=新WAR2015ContestModel();            //遍历并映射到强类型模型
            的foreach(在nvc.AllKeys串KVP)
            {
                。PI的PropertyInfo = model.GetType()的getProperty(KVP,BindingFlags.Public | BindingFlags.Instance);
                如果(PI!= NULL)
                {
                    pi.SetValue(型号,雷士照明[KVP],NULL);
                }
            }            model.Image = HttpContext.Current.Request.Files [形象];
        }
        赶上(异常前)
        {        }
    }


解决方案

您不能上传文件(即任意的二进制数据)使用JSON作为JSON是一种文本格式。你将不得不使用多部分表单数据。

  //创建控制器模型
VAR模型=新FORMDATA();
model.append('名称',$ .trim($ contestForm.find('[NAME =农布雷])。VAL())+''+ $ .trim($ contestForm.find('[NAME = apellido])VAL()))。
model.append(电子邮件,$ .trim($ contestForm.find('[NAME =电子邮件])VAL()与toLowerCase()));
model.append('市',$ .trim($ contestForm.find('[NAME =cuidad])VAL()));
model.append(标题,$ .trim($ contestForm.find('[NAME =标题])VAL()));
model.append('说明',$ .trim($ contestForm.find('[NAME =说明])VAL()));
model.append('国家code','合');
model.append('形象',$ contestForm.find('[NAME =文件-ES]')[0] .files [0]); //这对于确保该文件$阿贾克斯({
    网址:'/一把umbraco / API / ControllerName / CreateContestEntry',
    输入:POST,
    数据类型:JSON,
    数据:模型,
    过程数据:假的,
    的contentType:假的,不// JSON
    完成:功能(数据){
        VAR mediaId = $ .parseJSON(data.responseText); //?    },
    错误:功能(响应){
        的console.log(response.responseText);
    }
});

I need to post to an Api Controller w/ JSON (preferably) with ONE request. This is the way I've always done it, since I'm using Umbraco. I know you can use SurfaceControllers but I need to do a non-postback and cannot use custom model since I need Umbraco's TemplatePage model.

I'm open to suggestions.

The issue is passing data AND a file (image uploaded). I've never had to do this before, and my property is coming up empty (null).

I've looked at quite a bit of blogs but can't seem to get the image's data passed.

public class SomeModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string City { get; set; }
    public HttpPostedFileBase Image { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string CountryCode { get; set; }
}


    [HttpPost]
    public void CreateContestEntry(SomeModelmodel)
    {
        // model.Image is always null
        // .. get image here - the other properties no issues
    }

jQuery

    // create model for controller
    var model = {
        Name: $.trim($contestForm.find('[name="nombre"]').val()) + ' ' + $.trim($contestForm.find('[name="apellido"]').val()),
        Email: $.trim($contestForm.find('[name="email"]').val().toLowerCase()),
        City: $.trim($contestForm.find('[name="cuidad"]').val()),
        Title: $.trim($contestForm.find('[name="title"]').val()),
        Description: $.trim($contestForm.find('[name="description"]').val()),
        CountryCode: 'co',
        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: JSON.stringify(model),
        //data: $('#test-form').serialize(),  // tried this and using FormData()
        processData: false,
        async: false,
        contentType: 'application/json; charset=utf-8',
        complete: function (data) {

        },
        error: function (response) {
            console.log(response.responseText);
        }
    });

Blogs I've looked at:


When I tried the FormData and $('#form1').serialize() approach, my provider.FileData and provider.FormData were always empty as well. I removed the model param from the method and the breakpoints were hitting when I switched it up.

    [HttpPost]
    public void CreateContestEntry()
    {
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            // Read the form data.
            Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                // empty
            }

            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    // empty
                }
            }
            //return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch(Exception ex)
        {

        }
    }


SOLUTION:

Going off of @Musa's answer, here's the Api Controller code. I mapped the NameValueCollection to my model.

    [HttpPost]
    public void CreateContestEntry()
    {
        try
        {
            // get variables first
            NameValueCollection nvc = HttpContext.Current.Request.Form;
            var model = new WAR2015ContestModel();

            // iterate through and map to strongly typed model
            foreach (string kvp in nvc.AllKeys)
            {
                PropertyInfo pi = model.GetType().GetProperty(kvp, BindingFlags.Public | BindingFlags.Instance);
                if (pi != null)
                {
                    pi.SetValue(model, nvc[kvp], null);
                }
            }

            model.Image = HttpContext.Current.Request.Files["Image"];
        }
        catch(Exception ex)
        {

        }
    }

解决方案

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

这篇关于邮政JSON数据和文件的Web API - jQuery的/ MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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