Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I embed an uploaded binary files (ASCII-8BIT) in an XML (UTF-8)?

I have a file which is uploaded via a regular form_for, this gives me a ActionDispatch::Http::UploadedFile object in the params hash on which I can call .read to get the content. I now need to embed the file in an XML document. I'm using a regular Ruby string for now to construct the XML. The default encoding for a Rails string is utf-8.

Therefore I get the error Encoding::UndefinedConversionError, "\x89" from ASCII-8BIT to UTF-8.

This happens for the following files:

what-matters-now-1.pdf: application/octet-stream; charset=binary
example.csv: text/plain; charset=utf-8
investigations.png: image/png; charset=binary

It does not happen for:

my_test.txt: text/plain; charset=us-ascii

I have tried changing the encoding, but I get the same error:

params[:file].read.encode('utf-8')
like image 676
Kris Avatar asked Dec 04 '22 04:12

Kris


1 Answers

I had the same problem (error) while trying to open and write a picture. It succeeded after adding "wb" as rights to the open method. Earlier, it was "w"

like image 131
babttz Avatar answered Dec 30 '22 02:12

babttz