Errno::ENOENT (No such file or directory @ rb_sysopen

后端 未结 2 1412
萌比男神i
萌比男神i 2020-12-29 23:33

I want to write something to a file.

# where userid is any intger [sic]
path = Rails.root + \"public/system/users/#{user.id}/style/img.jpg\" 
File.open(path,         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 23:53

    File.open(..., 'w') creates a file if it does not exist. Nobody promised it will create a directory tree for it.

    Another thing, one should use File#join to build directory path, rather than dumb string concatenation.

    path = File.join Rails.root, 'public', 'system', 'users', user.id.to_s, 'style'
    
    FileUtils.mkdir_p(path) unless File.exist?(path) 
    File.open(File.join(path, 'img.jpg'), 'wb') do |file|
      file.puts f.read
    end
    

提交回复
热议问题