You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Shrine保存PDF文件时遭遇编码错误的解决问询

Fixing Encoding Error When Saving PDFs with Shrine

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_type with the :mimemagic analyzer will correctly identify the PDF’s MIME type (application/pdf)
  • :validation_helpers lets 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_uri and :logging don’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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:56:05