How to save files on separate servers by extension

3

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?

    
asked by anonymous 06.01.2017 / 18:27

1 answer

4

I will not go into detail about MultipartFormDataStreamProvider . It could be a bit long, so I'll just show you how to modify your code to do what you want.

First, since you want to create a folder with the name of the extension if it does not exist, you need to create the method for this. For simplicity, you can use the method below:

private String CriarDiretorioSeNaoExistir(string path)
    {
        var returnPath = HttpContext.Current.Server.MapPath(path);

        if (!Directory.Exists(returnPath))
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));

        return returnPath;
    }

It simply checks to see if the directory exists. If it does not exist it will create. And as a return it returns the full path, ie its fileSaveLocation .

After this, we will only move the saved file to the new directory, like this:

File.Move(file.LocalFileName,
           Path.Combine(CriarDiretorioSeNaoExistir(Path.Combine("~/Arquivos/Uploads", file.LocalFileName.Split('.').LastOrDefault())),
           file.LocalFileName.Split('\').LastOrDefault()));

In this way we are getting the file saved with file.LocalFileName and moving to the new folder (which comes after the comma). And in the same method we are already checking and creating the directory if it does not exist (feel free to separate if you find it necessary).

Your complete code will look like this:

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));
              File.Move(file.LocalFileName,
                    Path.Combine(CriarDiretorioSeNaoExistir(Path.Combine("~/Arquivos/Uploads", file.LocalFileName.Split('.').LastOrDefault())),
                    file.LocalFileName.Split('\').LastOrDefault()));
        }
        // OK se tudo deu certo.
        return Request.CreateResponse(HttpStatusCode.OK, files);
    }
    catch (System.Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}


private String CriarDiretorioSeNaoExistir(string path)
{
    var returnPath = HttpContext.Current.Server.MapPath(path);

    if (!Directory.Exists(returnPath))
        Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));

    return returnPath;
}
    
06.01.2017 / 21:00