>我正在上传一个文件,该文件使用 carrierwave 保存在用户数据库中。使用文件更新后,我想调用将该文件复制到其他位置的操作。我的问题是,当我调用该操作时,它会给我这个 erro (Errno::EISDIR - Is a directory @ rb_sysopen)
,因为它无法识别创建的文件,但是如果我刷新文件在数据库中(如果我在其他位置而不是更新中调用copy_file操作它工作得很好,但我想仅在用户上传时才复制文件)。
这是我的两个操作,更新和运行更新调用后copy_file:
def copy_file
require "fileutils"
my_dir = Dir['./public/'+current_user.personal_file_url.to_s]
my_dir.each do |filename|
# name = File.basename('data', '.xml')[0,4]
dest_folder = "./public/files/"
FileUtils.cp(filename, dest_folder + "data.xml")
# File.rename(filename, dest_folder + "/" + "data" + File.extname(filename))
end
bat_file
#redirect_to personal_performance_path
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update #upload personal file
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to :back, notice: 'File was sucessfully uploaded!' }
format.json { render :show, status: :ok, location: @user }
# copy_file #make a copy of the uploaded file in public/files/data.xml for running in the bat file
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
copy_file
end
TempFile
方法:
您可以通过几种方式执行此操作,我最好为其创建一个模块,您可以根据需要执行此操作:
require 'tempfile'
module Temp
def copy_file(file1, file2)
file = TempFile.new(file1) #<= name your temp file
# the easiest way to do this is just to open the files and append to them
File.open(file2).each_line do |s|
File.open(file) { |tmp| tmp.puts(s) }
# you can choose to either truncate file2 or delete depending on what you need to do, you could also give it another argument in order to write to another file etc..
end
file.unlink #<= delete the tempfile
end
end
Temp.copy_file('test', 'example.txt')
这是对使用临时文件的基本了解
下面是一个复制模块的示例,您可以轻松地将临时文件集成到其中。