使用Shrine保存PDF文件时遭遇编码错误的解决问询
First: Yes, Shrine Absolutely Supports Binary Files
Shrine is built to handle all types of binary files—PDFs, images, videos, archives, you name it. The error you’re hitting isn’t a limitation of Shrine; it’s a simple issue with how you’re opening the local PDF file.
Why the Error Happens
When you use File.open('my_pdf.pdf') without specifying a mode, Ruby defaults to text mode. In text mode, Ruby tries to convert the file’s raw bytes (stored as ASCII-8BIT for binary files) to UTF-8, which fails because PDFs contain non-UTF-8 compatible bytes (like the \xFE in your error message).
The Fix: Open the File in Binary Mode
To resolve this, open your PDF with the binary mode flag 'rb' (read binary) to tell Ruby to treat the file as raw, unencoded data:
my_model.image = File.open('my_pdf.pdf', 'rb')
This skips any encoding conversion entirely, which is exactly what we need for binary files like PDFs.
Checking Your Uploader Setup
Looking at your DocumentUploader code, your plugin setup is already well-suited for PDFs:
:determine_mime_typewith the:mimemagicanalyzer will correctly identify the PDF’s MIME type (application/pdf):validation_helperslets you add checks to ensure only PDFs are uploaded (e.g.,validate_mime_type_inclusion ['application/pdf']if you haven’t added this yet)- Plugins like
:data_uriand:loggingdon’t interfere with binary file handling at all
Bonus: Handling Form Uploads
If you’re accepting PDFs via a web form (e.g., in Rails), you don’t need to worry about this encoding issue—Rails automatically provides uploaded files as Tempfile objects that are already in binary mode. You can pass them directly to Shrine without extra steps:
my_model.image = params[:my_model][:image]
内容的提问来源于stack exchange,提问作者rwehresmann

