I have a WEB API
that receives a file via POST
it follows the Controller
code:
public async Task<HttpResponseMessage> Post()
{
// Ver se POST é MultiPart?
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
// Preparar CustomMultipartFormDataStreamProvider para carga de dados
// (veja mais abaixo)
string fileSaveLocation = HttpContext.Current.Server.MapPath("~/Arquivos/Uploads");
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
List<string> files = new List<string>();
try
{
// Ler conteúdo da requisição para CustomMultipartFormDataStreamProvider.
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
}
// OK se tudo deu certo.
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
My method: CustomMultipartFormDataStreamProvider
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path)
: base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName;
}
}
I am saving the files in a Files / Uploads folder however, I need to save the files that are received in separate folders, for example Word into a folder named Word etc ...
The way I'm doing now is a little bureaucratic but it works. I have a Utilities class that upon receipt of the file it makes a copy of the file to the folder where it should stay and deletes the file inside the Files / Uploads folder.
Is there a way to simplify this, which through controller Post
do I identify the file extension and save it to its folder on the server?