【发布时间】:2011-03-24 13:09:51
【问题描述】:
我想:点击按钮 => 选择一个文件 => 点击“确定”(或双击文件) => 自动启动上传。
如何使用 rails 实现这一点?
【问题讨论】:
-
Google for Uploadify、Paperclip 或 Carrierwave;试一试,然后提出有关实施的问题
标签: javascript html ruby-on-rails
我想:点击按钮 => 选择一个文件 => 点击“确定”(或双击文件) => 自动启动上传。
如何使用 rails 实现这一点?
【问题讨论】:
标签: javascript html ruby-on-rails
控制器
def file_upload
begin
ModelName.file_upload(params[:upload])
flash[:notice] = "File has been uploaded successfully"
redirect_to :action => "method_name"
rescue Exception => e
flash[:error] = "Error with upload! Please retry."
end
end
型号
def self.file_upload(upload)
name = upload.original_filename
directory = "#{DIR_PATH}"
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, "wb") { |f| f.write(upload.read) }
end
查看
<% form_tag({:controller => "controller_name", :action => "file_upload"}, {:multipart => true}) do%>
<div class="fileinputs">
<input type="file" name="upload" id="upload" class="file" onchange="this.form.submit();" />
<div class="fakefile">
<input class="upload_btn"/>
</div>
</div>
<% end %>
CSS
div.fileinputs {
position: relative;
}
div.fakefile {
position: absolute;
top: 0px;
left: 0px;
z-index: 1;
}
input.file {
position: relative;
text-align: right;
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
z-index: 2;
}
input.upload_btn {
background:transparent url(/images/upload_btn.gif) no-repeat scroll 0px 0px ;
width:79px;
height:26px;
cursor:pointer;
border:0px;
}
input.upload_btn:hover {
background:transparent url(/images/upload_btn.gif) no-repeat scroll 0px -40px ;
}
【讨论】:
看看回形针 gem,假设您使用 rails 3,应该涵盖所有内容
https://github.com/thoughtbot/paperclip
http://www.jameswilding.net/blog/2010/07/paperclip-rails-3/
【讨论】:
您可以按照建议使用回形针,但我从您的问题中了解到您想取消“提交”按钮?
让 javascript 监听文件字段上的 onChange 事件并提交表单:
:onchange => "this.form.submit();"
【讨论】: