WebAPI method that takes a file upload and additional arguments

后端 未结 5 734
野性不改
野性不改 2020-12-04 18:32

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.

How would I write a ASP.NET WebAPI

5条回答
  •  遥遥无期
    2020-12-04 18:53

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

    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 CustomData { get; set; }
    
        public CustomMultipartFileStreamProvider()
        {
            CustomData = new List();
        }
    
        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 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 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);
        }
    }
    

提交回复
热议问题