欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

rails遍历某文件夹下所有目录文件上传到mongodb gridfs

程序员文章站 2022-03-25 09:11:43
...
相关gem包  gem 'mongo'
方法一:

task test_file: :environment do

file_path = "/Users/jamst/public/test"

      def traverse_dir(filepath)
        if File.directory?(filepath)
          puts "Dirs:" + filepath
          Dir.foreach(filepath) do |filename|
            if filename != "." and filename != ".."
              traverse_dir(filepath + "/" + filename)
            end
          end
        else
          file = File.open(filepath) 
          file_name = filepath[1..-1]
          # 文件写入mongondb
          grid = $mongo.database.fs
          grid.upload_from_stream(file_name, file)
          # key写入mysql
          @avatar = Avatar.new
          @avatar.attachment_file_name = file_name
          @avatar.attachment_content_type = file.content_type
          @avatar.save
          puts "Files:" + filepath
        end
      end
      traverse_dir(file_path)
end
 
 
改进方法二:
task test_file: :environment do
  root = Rails.root.join("public/test/").to_s
      Dir["#{root}**/*"].each do |f|
        file = File.open(f) 
        next if File.directory?(f)
        @avatar = Avatar.new
            grid = $mongo.database.fs
            file_name = f.sub(root,'')
            file_name = "jamst/customer_order/#{file_name}"
            grid.upload_from_stream(file_name, file)
            @avatar.attachment_file_name = file_name
            @avatar.attachment_content_type = ".jpg"
            @avatar.save
            puts "Files: #{file_name}" 
      end
end
 
方法三:rails的Find类提供了find方法
require  'find'
Find.find("/usr/local/src") do |filename|
    p filename
end


关于在rails中集成mongodb gridfs的调用看连接

https://github.com/jamst/mongo_image_demo

感谢大牛blog指导http://www.tuicool.com/articles/EnUnqeN
相关标签: mongodb rails