How to get local file name using MultipartFormDataStreamProvider in ASP.NET MVC?

What is MultipartFormDataStreamProvider?

The stream provider looks at the Content-Disposition header field and determines an output Stream based on the presence of a filename parameter. If a filename parameter is present in the Content-Disposition header field then the body part is written to a FileStream, otherwise it is written to a MemoryStream. This makes it convenient to process MIME Multipart HTML Form data which is a combination of form data and file content.

namespace DotNetMinds
{

using System;

using System.Net.Http;


public
class
CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider

{


///
<summary>


///


///
</summary>


///
<param name=”path“></param>


public CustomMultipartFormDataStreamProvider(string path)

: base(path)

{

}


///
<summary>


///


///
</summary>


///
<param name=”headers“></param>


///
<returns></returns>


public
override
string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)

{


try

{


string fileName = Guid.NewGuid().ToString();


if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName))

{


var name = headers.ContentDisposition.FileName.Replace(“\””, string.Empty);

fileName += System.IO.Path.GetExtension(name);

}


return fileName;

}


catch (Exception ex)

{


return
Guid.NewGuid().ToString();

}

}

}

}


Recommended Book for MVC : List of Some Important books for .NET Framework, C#, MVC, WCF


 

(Visited 372 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *