带有额外参数的Webapi ajax表单数据上传 [英] Webapi ajax formdata upload with extra parameters

查看:25
本文介绍了带有额外参数的Webapi ajax表单数据上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 jQuery ajax 上传文件,但想在 webapi 方法上添加一些参数,这里是:

var data = new FormData();data.append("file", $("#file")[0].files[0]);data.append("myParameter", "test");//有了这个参数,我得到 404$.ajax({url: '/api/my/upload/',数据:数据,缓存:假,内容类型:假,过程数据:假,类型:'POST',成功:功能(数据){控制台日志(数据);}});

Webapi 控制器:

公共类 MyController : ApiController{公共字符串上传(字符串 myParameter){返回 System.Web.HttpContext.Current.Request.Files.Count.ToString() + "/" + myParameter;}}

没有 myParameter 一切正常,但是当我在 formdata 和 api 方法中包含 myParameter 时,我得到 404,有机会让它工作吗?

解决方案

发布 FormData 对象会导致内容类型为 multipart/form-data 的请求.您必须像这样阅读请求内容:

[HttpPost]公共异步任务上传(){var provider = new MultipartFormDataStreamProvider("C:\Somefolder");等待 Request.Content.ReadAsMultipartAsync(provider);var myParameter = provider.FormData.GetValues("myParameter").FirstOrDefault();var count = provider.FileData.Count;返回计数 + "/" + myParameter;}

顺便说一句,这会将文件保存在指定的路径中,即 C:\SomeFolder,您可以使用 provider.FileData[0].LocalFileName; 获取本地文件名;

请查看MSDN 代码示例Henrik 的博客文章.>

I'm using jQuery ajax to upload file but want to add some parameters on webapi method, here is:

var data = new FormData();
data.append("file", $("#file")[0].files[0]);
data.append("myParameter", "test"); // with this param i get 404

$.ajax({
    url: '/api/my/upload/',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        console.log(data);
    }
});

The Webapi controller:

public class MyController : ApiController
{
    public string Upload(string myParameter)
    {
        return System.Web.HttpContext.Current.Request.Files.Count.ToString() + " / " + myParameter;
    }
}

Without myParameter everything work but when I include myParameter on formdata and api method I get 404, any chance to make it work?

解决方案

Posting the FormData object results in a request with content type multipart/form-data. You have to read the request content like so:

[HttpPost]
public async Task<string> Upload()
{
    var provider = new MultipartFormDataStreamProvider("C:\Somefolder");
    await Request.Content.ReadAsMultipartAsync(provider);

    var myParameter = provider.FormData.GetValues("myParameter").FirstOrDefault();
    var count = provider.FileData.Count;

    return count + " / " + myParameter;
}

BTW, this will save the file in the path specified, which is C:\SomeFolder and you can get the local file name using provider.FileData[0].LocalFileName;

Please take a look at MSDN code sample and Henrik's blog entry.

这篇关于带有额外参数的Webapi ajax表单数据上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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