问题描述
使用 ruby on rails 文件上传工作正常.现在我需要验证我的上传.单击上传后未选择任何文件时,它应该验证并显示错误消息.请帮助我提供此错误验证的代码.
The file uploading is working properly using ruby on rails. Now i need to validate my uploading. It should validate and display error message when no file is selected after clicking upload. Please help me with a code for this error validation.
我的视图文件是 (uploadfile.html.erb):
My view file is (uploadfile.html.erb):
<h1>File Upload</h1>
<%= form_tag({action: :uploadFile}, multipart: true) do %>
<p><label for="upload_file">Select File</label>
<%= error_messages_for :data_file %>
<%= file_field 'upload', 'datafile' %></p>
<%= submit_tag "Upload" %>
<%end%>
我的控制器文件是 (upload_controller.rb):
My controller file is (upload_controller.rb):
class UploadController < ApplicationController
def uploadFile
post = DataFile.save(params[:upload])
render :text => "File has been uploaded successfully"
end
end
我的模型文件是 (data_file.rb):
My model file is (data_file.rb):
class DataFile < ActiveRecord::Base
attr_accessor :upload
validates_attachment_presence :upload unless :upload
def self.save(upload)
name = upload['datafile'].original_filename
directory = "public/data"
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
end
end
推荐答案
如果您使用的是 paperclip gem,你可以在你的模型中这样做.
If you are using paperclip gem,you can do like this in your Model.
validates_attachment_presence :datafile unless :datafile
检查上传的文件是否存在.
It checks the existence of uploaded file.
更新
要显示错误消息,只需将此行添加到您的表单中
For displaying the error messages,just add this line to your form
<%= error_messages_for :upload_file %> #Assuming your model name is `upload_file`
这篇关于在 ruby on rails 中上传文件时出现错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!