回形针文件上传 [英] Paper clip files upload

查看:60
本文介绍了回形针文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,在同一个表单中,我有两个上传,一个是图像类型,另一个是用于 doc、excel 和 PDF 等.我对两者都使用 gem 'paper-clip'.首先我想知道如何自定义和配置回形针以上传两种类型,第二我想限制两个字段不上传其他类型.类似图像字段不应接受其他内容类型,反之亦然.

I have a scenario, In the same form, I have two uploads one is of image type while other one is for doc,excel and PDF etc. I am using gem 'paper-clip' for both. first I want to know how to customize and configure paper clip to upload both types, second I want to restrict both fields not to upload other type. like images fields should not accept other content type similarly vice versa.

推荐答案

可以查看

回形针上传文件:--1) 在 Gemfile 中将 gem 包含在您的 Gemfile 中:

Paperclip Upload file :-- 1) In Gemfile Include the gem in your Gemfile:

 gem "paperclip", "~> 3.0"

如果你仍在使用 Rails 2.3.x,你应该这样做:

If you're still using Rails 2.3.x, you should do this instead:

 gem "paperclip", "~> 2.7"

2)在你的模型中

class User < ActiveRecord::Base
  attr_accessible :img_avatar, :file_avatar
   has_attached_file :img_avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
   has_attached_file :file_avatar, :default_url => "/files/:style/missing.doc"
end

3) 在您的迁移中:

 class AddAvatarColumnsToUsers < ActiveRecord::Migration
    def self.up
     add_attachment :users, :img_avatar
     add_attachment :users, :file_avatar  
    end

   def self.down
     remove_attachment :users, :img_avatar
     remove_attachment :users, :file_avatar
   end
 end

在您的编辑和新视图中:

In your edit and new views:

   <%= form_for @user, :url => users_path, :html => { :multipart => true } do |form| %>
    <%= form.file_field :img_avatar %>
    <%= form.file_field :file_avatar %>
  <% end %>

在您的控制器中:

def create
 @user = User.create( params[:user] )
 if ["jpg,"jpeg","gif", "png"].include? File.extname(params[:img_avatar])
  @user.img_avatar = params[:img_avatar]
 elsif ["doc","docx","pdf","xls","xlsx"].include?File.extname(params[:file_avatar])
  @user.file_avatar = params[:file_avatar]
else
  flash[:message] = "You are uploading wrong file" #render flash message
end 

结束

谢谢

这篇关于回形针文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆