Convert file to Byte Array [duplicate]

1

I am trying to convert a received file in FileUpload (ASP.NET tool) to an array and then the array to a string .

But when trying to use Encoding Visual Studio accuses an error saying that this class only accepts a string to convert to array in>.

Follow the code:

if (FileUploadControl.HasFile)
{
    try
    {
        if (FileUploadControl.PostedFile.ContentType == "image/jpeg")
        {
            if (FileUploadControl.PostedFile.ContentLength < 102400)
            {
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] arrayImg = encoding.GetBytes(FileUploadControl.PostedFile);
                String img64Produto = Convert.ToBase64String(arrayImg);

            }
            else
                //StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
                ClientScript.RegisterClientScriptBlock(Page.GetType(), "msgErroLogin", "alert('O arquivo deve ser menor que 100KB!');", true);
        }
        else
            //StatusLabel.Text = "Upload status: Only JPEG files are accepted!";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "msgErroLogin", "alert('Apenas .jpeg são suportados!');", true);
    }
    catch (Exception ex)
    {
        //StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        String msg = "O arquivo não pode ser carregado" + ex.Message;
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "msgErroLogin", "alert('O arquivo não pode ser carregado.');", true);
    }
}
    
asked by anonymous 27.11.2017 / 15:44

1 answer

1

What you're trying to do does not make sense, Encoding.GetBytes() is to generate the array bytes string.

The FileUpload itself has a property FileBytes that contains the bytes of the file.

byte[] arrayImg = FileUploadControl.FileBytes;
    
27.11.2017 / 15:51