Convert file to Array of bytes

Asked

Viewed 1,350 times

1

I’m trying to convert a received file into FileUpload (ASP.NET tool) for a array of bytes and then the array for a string.

But when trying to use the Encoding Visual Studio accuses an error saying that this class only accepts one string to convert into array of bytes.

Follows 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);
    }
}

1 answer

1


What you’re trying to do doesn’t make sense, Encoding.GetBytes() is to generate the array of bytes string.

The very one FileUpload has a property FileBytes which contains the bytes of the archive.

byte[] arrayImg = FileUploadControl.FileBytes;
  • I used Fileuploadcontrol.Filebytes and it worked thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.