Home > Net >  C# - How to upload files to Azure Storage Blob (unknown phisic path)
C# - How to upload files to Azure Storage Blob (unknown phisic path)

Time:04-19

In my web application, I need to allow the user to choose an image from their machine and upload it, and have that image physically stored to my container in my storage in Azure.

The way to do this I have found in many places and it works for me, but with the IMPORTANT EXCEPTION that in all examples, they upload a file from their own machine and knowing or harcoding the physical path.

But as for security reasons, the input file cannot read the physical address of the client, I was forced to use the strategy of:

  1. I upload the image to the web server to a known path.
  2. I take that path, and I use it to upload to Azure Storage Blob.
  3. Confirmed this, I don't want that file to stay on the server, I just want it to be in my container, so I proceed to delete the file.
  4. I get the following exception:

The process cannot access the file. 'C:\My_folders\MyFile.jpg' because it is being used by another process.

Note: I tried using a project directory and also the temporary directory of the operating system. For both cases I get the same result.

So, in conclusion: I need to upload to Azure S Blob, but as far as I could find out, for that I need the physical path of the file, so I need to upload it to my server and from there upload it.

I would like you to help me with these options:

  1. To be able to upload it without the physical path. Or to be able to close the process I have now, ensuring the deletion of the temporary file on the server.
  2. Any of your suggestions.

Thank you very much! _________________________ CODE ________________________ FRONT

<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<div >
        <div  id="conten_CargaImagenes">
            <div >
                <div >
                    <h3  id="tituloAbmHorarios">
                        <i ></i> Nueva Imagen
                    </h3>
                </div>
                
                <div >
                    <div >

                        <div >
                            <div >
                                <input asp-for="File"  />
                                <label id="fileImageLabel" asp-for="File" ></label>
                            </div>
                        </div>

                        <div >
                            <button type="button"  onclick="GuardarImagen()">
                                <i ></i> Grabar Imagen
                            </button>
                        </div>

                    </div>
                </div>
            </div>
        </div>
</div>

JS Method

function GuardarImagen() {

    var form = $('#fileUploadForm')[0];

    var model = new FormData(form);
    model.append('IdComercio', $('#Id').val());

    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "/Comercios/GrabaFile",
        data: model,
        processData: false,
        contentType: false,
        cache: false,
        timeout: 600000,
        success: function (e) {

            if (!e.isError) {
                $("#File").val(null);
                document.getElementById("fileImageLabel").innerHTML = '';

                toastr.success(textos.imagenGrabadaOk, { timeOut: 2000 });
                InjectarNuevaImagenEnPantalla(e.data);
            } else {
                toastr.error(e.data, { timeOut: 2000 });
            }
        }
    });
}

BACK

[HttpPost]
        public ReturnData GrabaFile(UploadFileComercioDTO pData)
        {

            if (pData.File != null)
            {
                try
                {
                    var result = UploaderFilesService.UploadToAzure(pData.File, FolderPath, pData.IdComercio.ToString());
                    
                }
                catch (Exception ex)
                {
                    do something...
                }
            }
            else
            {
                return messageError
            }
        }


public static ReturnData UploadToAzure(IFormFile pFile, string pFolder, string pIdComercio)
        {
            ReturnData returnData = new();

            if (pFile != null)
            {
                if (ValidaFile(pFile.ContentType, pFile.Length))
                {
                    try
                    {
                        string nombreOriginal = pFile.FileName;
                        var nombrePartes = nombreOriginal.Split(".");
                        string extension = nombrePartes[(nombrePartes.Length - 1)];

                        string nombreFinal = GenerarTextoUnico()   "."   extension;
                        string soloNOmbre = nombreFinal; // ****

                        pFolder = Path.GetTempPath(); // *************
                        string filePath = Path.Combine(pFolder, nombreFinal);

                        using (var stream = File.Create(filePath))
                        {
                            pFile.CopyTo(stream);
                        }

                        string connectionString = "adsfasfasdfasdf";
                        string containerName = "asdfasdf";

                        nombreFinal = pIdComercio   "/"   nombreFinal;

                        BlobContainerClient container = new BlobContainerClient(connectionString, containerName);
                        var upload = container.UploadBlob(nombreFinal, File.OpenRead(filePath));

                        try
                        {
                            File.Delete(filePath);
                        }
                        catch (IOException e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        ...
                    }
                }
                else
                {
                    ...
                }
            }
            else
            {
                ...
            }

            return returnData;
        }

CodePudding user response:

I found the problem and the solution.

The problem was that it was not closing the stream when uploading.

The modification to make was in the UploadToAzure method, change the following line

var upload = container.UploadBlob(finalName, File.OpenRead(filePath));

for this

using (var stream = File.OpenRead(filePath))
{
   var upload = container.UploadBlob(endName, stream);
}

That way when I exit using the stream is already closed and I can proceed to delete it.

  • Related