0

我是 Rails 新手,一直在关注 YouTube https://www.youtube.com/watch?v=70Pu_28yvdI上的教程,已经到了第 40 分钟左右,当我尝试创建新帖子并附上图片时,我得到了错误图像的扩展名与其内容不匹配,我编写了与他完全相同的代码并不断收到错误。非常感谢你的帮助。

post.rb 文件

class Post < ActiveRecord::Base
    belongs_to  :user
    has_attached_file :image, styles: { medium: "700x500#", small: "350x250" }
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end

post_controller.rb 文件

class PostsController < ApplicationController
    before_action :find_post, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, except: [:index, :show]

    def index
        @post = Post.all.order("created_at DESC")   
    end

    def show
    end

    def new
        @post = current_user.posts.build
    end

    def create
        @post = current_user.posts.build(post_params)
        if @post.save
            redirect_to @post
        else
            render 'new'
        end 
    end

    def edit    
    end

    def update
        if @post.update(post_params)
            redirect_to @post
        else
            render 'edit'
        end 
    end

    def destroy
        @post.destroy
        redirect_to root_path   
    end

    private

    def find_post
        @post = Post.find(params[:id])
    end

    def post_params
        params.require(:post).permit(:title, :link, :description, :image)
    end

end

20150728130528_add_attachment_image_to_posts.rb 文件

class AddAttachmentImageToPosts < ActiveRecord::Migration
  def self.up
    change_table :posts do |t|
      t.attachment :image
    end
  end

  def self.down
    remove_attachment :posts, :image
  end
end
4

1 回答 1

0

如果您在 Windows 上(来自https://github.com/thoughtbot/paperclip):

如果您使用 Windows 7+ 作为开发环境,您可能需要手动安装 file.exe 应用程序。Paperclip 4+ 中的文件欺骗系统依赖于此;如果您没有让它工作,您将收到验证失败:上传文件的扩展名与其内容不匹配。错误。

确保您使用与验证相同的图像类型:

您应该确保验证文件仅是您明确希望支持的那些 MIME 类型。否则,如果用户上传带有恶意 HTML 有效负载的文件,您可能会受到 XSS 攻击。

如果您只对图像感兴趣,请将允许的 content_types 限制为 image-y :

validates_attachment :avatar,
      :content_type => { :content_type => ["image/jpeg", "image/gif", "image/png"] }

Paperclip::ContentTypeDetector 将尝试将文件的扩展名与推断的 content_type 匹配,而不管文件的实际内容如何。

于 2015-07-28T17:42:09.693 回答