Skip to main content
Participant
September 14, 2017
Answered

CF9 Converting a string to Binary

  • September 14, 2017
  • 1 reply
  • 1155 views

I would like to know why these two values are different.

What is the correct way to convert a string to binary.

<cfhttp url="https://image.freepik.com/free-icon/apple-logo_318-40184.jpg" method="get" getasbinary="yes" result="result">

<cfhttp url="https://image.freepik.com/free-icon/apple-logo_318-40184.jpg" method="get" getasbinary="no" result="result2">

<cfdump var="#result.fileContent#">

<cfdump var="#toBinary(toBase64(result2.fileContent.toString()))#"><cfabort>

<cfheader name="Content-Disposition" value="inline; filename=logo.jpg">

<cfcontent type="image/jpeg; charset=iso-8859-1" variable="#result.fileContent#">

In my real world example, I am actually doing this with FileRead and I use FileRead and not FileReadBinary (but the same problem exists) because I need to crop out a couple of blanks lines in a physical file before converting it to binary, and that file is created by a third party software which I cannot alter.

Can anyone help?

Thanks in advance,

Allan

P.S. I also tried charsetDecode( result2.fileContent.toString(, "utf-8" ) but with the same result as toBinary(toBase64(result2.fileContent.toString()))

This topic has been closed for replies.
Correct answer haxtbh

You want to be getting the Byte Array of the fileContent rather then String.

Using getAsBinary attribute returns the Byte Array (Binary) value of the response, so by using the toByteArray() function instead of toString() you get the same content back.

You don't need to use toBinary either as the Byte Array is the binary result.

<cfdump var="#result2.fileContent.toByteArray()#"><cfabort>

https://trycf.com/gist/8eb85bf333996a65312b352ff63b91eb/acf2016?theme=monokai

1 reply

haxtbhCorrect answer
Inspiring
September 15, 2017

You want to be getting the Byte Array of the fileContent rather then String.

Using getAsBinary attribute returns the Byte Array (Binary) value of the response, so by using the toByteArray() function instead of toString() you get the same content back.

You don't need to use toBinary either as the Byte Array is the binary result.

<cfdump var="#result2.fileContent.toByteArray()#"><cfabort>

https://trycf.com/gist/8eb85bf333996a65312b352ff63b91eb/acf2016?theme=monokai