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

Rails 如何通过本地文件路径将文件存入数据库binary字段

本地视频文件写入数据库字段的实现方案

核心逻辑说明

你的现有表结构已经配置了二进制类型的file字段,大小上限100MB,完全支持存储mp4文件的二进制内容。整个流程不需要额外依赖组件,直接通过Ruby原生文件读取能力就可以完成写入。

完善后的add_file控制器方法

def add_file
  # 取外部触发时传入的文件唯一标识(根据实际传参规则调整取值方式)
  unique_id = params[:file_uniq_id]
  
  # 拼接生成文件的完整本地路径
  record_path = "/opt/program/records/#{unique_id}_record.mp4"

  # 前置校验:文件不存在时直接返回错误,避免触发系统异常
  return render plain: "Video file not found", status: 404 unless File.exist?(record_path)

  # 匹配需要关联的Article业务记录(替换为实际业务的匹配规则)
  target_record = Article.find(unique_id)
  return render plain: "Target article record not exist", status: 404 unless target_record

  # 读取文件二进制内容,赋值给file字段
  target_record.file = File.binread(record_path)

  # 持久化保存
  if target_record.save
    render plain: "File stored successfully", status: 200
  else
    render plain: "Save failed: #{target_record.errors.full_messages.join('; ')}", status: 500
  end
end

落地注意点

  • 读取mp4这类二进制文件必须使用*File.binread*,不能使用普通的文本读取方法,否则会因为编码转换损坏文件内容,写入后无法正常播放
  • 可以在读取文件前增加大小判断:File.size(record_path),确认不超过schema里配置的100MB上限,避免保存时触发数据库字段长度异常
  • 这种把大文件直接存在数据库的方式不适合长期生产使用,会拖慢数据库查询效率、提升备份成本,当前实现是严格匹配你现有表结构的最小可用方案

内容的提问来源于stack exchange,提问作者schande

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 14:45:03