的WebAPI方法,它接受文件的上传和附加参数 [英] WebAPI method that takes a file upload and additional arguments

查看:3614
本文介绍了的WebAPI方法,它接受文件的上传和附加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要上传的文件和文件一些额外的信息一起发送,假设一个字符串foo和一个int吧。

I want to upload a file and send along with the file some additional information, let's say a string foo and an int bar.

我怎么会写接收文件上传,一个字符串,一个int一个ASP.NET的WebAPI控制器的方法?

我的javascript:

My JavaScript:

var fileInput = document.querySelector("#filePicker");
var formData = new FormData();
formData.append("file", fileInput.files[0]);
formData.append("foo", "hello world!");
formData.append("bar", 42);

var options = {
   url: "/api/foo/upload",
   data: formData,
   processData: false // Prevents JQuery from transforming the data into a query string
};
$.ajax(options);

我的WebAPI控制器可以访问该文件是这样的:

My WebAPI controller can access the file like this:

public async Task<HttpResponseMessage> Upload()
{
    var streamProvider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(streamProvider);
    var fileStream = await streamProvider.Contents[0].ReadAsStreamAsync();
}

但它不是我清楚我怎么能在我的字符串和我INT得到。我想我大概可以说streamProvider.Content [1],或什么,但感觉超级讨厌的。

But it's not clear to me how I can get at my string and my int. I figure I can probably say streamProvider.Content[1], or whatever, but that feels super nasty.

什么是正确的方式©编写接受文件上传,一个字符串的WebAPI的动作,和一个int?

What's the Right Way© to write a WebAPI action that accepts a file upload, a string, and an int?

推荐答案

您可以创建自己的 MultipartFileStreamProvider 来访问额外的参数。

You can create your own MultipartFileStreamProvider to access the additional arguments.

在通过多形式的一部分,每个文件 ExecutePostProcessingAsync 我们循环并加载自定义数据(如果你只有一个文件,你只需要一个对象在的CustomData 列表)。

In ExecutePostProcessingAsync we loop through each file in multi-part form and load the custom data (if you only have one file you'll just have one object in the CustomData list).

class MyCustomData
{
    public int Foo { get; set; }
    public string Bar { get; set; }
}

class CustomMultipartFileStreamProvider : MultipartMemoryStreamProvider
{
    public List<MyCustomData> CustomData { get; set; }

    public CustomMultipartFileStreamProvider()
    {
        CustomData = new List<MyCustomData>();
    }

    public override Task ExecutePostProcessingAsync()
    {
        foreach (var file in Contents)
        {
            var parameters = file.Headers.ContentDisposition.Parameters;
            var data = new MyCustomData
            {
                Foo = int.Parse(GetNameHeaderValue(parameters, "Foo")),
                Bar = GetNameHeaderValue(parameters, "Bar"),
            };

            CustomData.Add(data);
        }

        return base.ExecutePostProcessingAsync();
    }

    private static string GetNameHeaderValue(ICollection<NameValueHeaderValue> headerValues, string name)
    {
        var nameValueHeader = headerValues.FirstOrDefault(
            x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

        return nameValueHeader != null ? nameValueHeader.Value : null;
    }
}

然后在你的控制器:

Then in your controller:

class UploadController : ApiController
{
    public async Task<HttpResponseMessage> Upload()
    {
        var streamProvider = new CustomMultipartFileStreamProvider();
        await Request.Content.ReadAsMultipartAsync(streamProvider);

        var fileStream = await streamProvider.Contents[0].ReadAsStreamAsync();
        var customData = streamProvider.CustomData;

        return Request.CreateResponse(HttpStatusCode.Created);
    }
}

这篇关于的WebAPI方法,它接受文件的上传和附加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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