Search code examples
file-uploadasp.net-web-apimultipartform-datamultipart

Unable to change file name after File Upload using WebApi MultipartFormDataStreamProvider


Im using WebApi to upload a file, but when I run

request.Content.ReadAsMultipartAsync(provider)

The file is uploaded but its file name is totally changed. I read something about that says that it is automatically made for security reasons. Anyway I want to store the file with the real file name. Any idea how to do it?


Solution

  • This simple override fix this issue

    public class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public MyMultipartFormDataStreamProvider(string path) : base(path)
        { }
    
        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            // override the filename which is stored by the provider (by default is bodypart_x)
            string originalFileName = headers.ContentDisposition.FileName.Trim('\"');
    
            return originalFileName;
        }
    }