Get an HttpPostedFileBase and convert to CloudFile (Azure Files) so you do not need to write to the File Server

0

Good people I have the following problem. The controller receives an HttpPostedFileBase and sends it to Azure and for this I need to write to a temporary folder.

I would like to know of a more elegant solution where you do not need to write to the Server disk. Summarizing send the HttpPostedFileBase direct to Azure with CloudFile. Because this solution seems to me to be more performative, if any idea please share.

Follow the code below:

 CloudStorageAccount _azureFile;

    public UploadArquivo()
    {
        _azureFile = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("azureFile"));
    }
    public void uploadArquivoAzure(HttpPostedFileBase arquivo, string caminhoArquivo)
    {
        //Escreve arquivo no caminho temporario
        arquivo.SaveAs(caminhoArquivo);

        // Criando o cliente do azure para acessar o storage
        CloudFileClient clienteArquivos = _azureFile.CreateCloudFileClient();

        // acessando o serviço de arquivos
        CloudFileShare compartilhamentoArquivos = clienteArquivos.GetShareReference("servicoArquivo");

        if (compartilhamentoArquivos.Exists())
        {
            // cria o diretorio raiz
            CloudFileDirectory dirRaiz = compartilhamentoArquivos.GetRootDirectoryReference();

            // criando o diretorio especifico
            CloudFileDirectory diretorio = dirRaiz.GetDirectoryReference("compartilhamentoArquivos");

            if (diretorio.Exists())
            {
                //Setando o arquivo e caminho do mesmo caminho do arquivo
                CloudFile arquivoEnviado = diretorio.GetFileReference(arquivo.FileName);


                arquivoEnviado.UploadFromFile(arquivo.);

                //arquivoEnviado.DownloadToFile(caminhoArquivo, FileMode.Create);

                //arquivoEnviado.UploadFromFile(caminhoArquivo);

            }
        }
    }

Any hint would help a lot.

    
asked by anonymous 20.07.2016 / 20:49

1 answer

1

To keep your file in memory without having to burn to disk, you should save your file to [System.IO.Stream.MemoryStream](https://msdn.microsoft.com/en-us/library/system.io.memorystream(v=vs.110).aspx) .

It would look something like this:

[HttpPost]
[Route("upload")]
public async Task<IHttpActionResult> Upload()
{
    var uploaded = await GravarNaMemoriaAsync(arquivo.InputStream);
    // ...
    EnviarParaNuvem(arquivo.FileName, uploaded);
}

private async Task<Stream> GravarNaMemoriaAsync(Stream stream)
{
        // Verify that this is an HTML Form file upload request
    if (!Request.Content.IsMimeMultipartContent("form-data"))
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

    // Create a stream provider for setting up output streams that saves the output under memory
    var streamProvider = new MultipartMemoryStreamProvider();

    // Read the MIME multipart content using the stream provider we just created.
    var bodyparts = await Request.Content.ReadAsMultipartAsync(streamProvider);
    var documentStream = await streamProvider.Contents[0].ReadAsStreamAsync();

    var buffer = new byte[documentStream.Length];
    await documentStream.ReadAsync(buffer, 0, buffer.Length);

    return documentStream;
}

Now, about submitting this one to Azure Storage, I believe you're not doing it the right way. You are using disk file synchronization capabilities with the cloud storage area. As if you were doing a "OneDrive" or "DropBox", and that's not quite what I see that you really want to do.

If I understand you, you send a file that they uploaded to your application and stored it in Azure Storage - and that's very correct. But you should store it in the Blobs area, inside an Azure container.

To do this, here is an example:

private void EnviarParaNuvem(string meuArquivo, Stream memoryStream)
{
    // Recuperar sua conta de armazenamento via connection string.
    var storageAccount = CloudStorageAccount.Parse(
        CloudConfigurationManager.GetSetting("StorageConnectionString"));

    // Cria um client blob.
    var blobClient = storageAccount.CreateCloudBlobClient();

    // Cria uma referencia para um container criado anteriormente.
    var container = blobClient.GetContainerReference("mycontainer");

    // Cria uma referencia para um blob com nome de "meuArquivo".
    var blockBlob = container.GetBlockBlobReference(meuArquivo);

    // Cria ou sobrescreve o "meuArquivo" com o conteúdo do seu MemoryStream.
    blockBlob.UploadFromStream(memoryStream);
} 

Source: How to store Blob files in Azure .

    
21.07.2016 / 10:06