RM6*_*M64 2 ruby ruby-on-rails rails-activestorage
如何将 activestorage 下载的输出写入临时文件。
后来每当我读出它时,它就变成了一个空字符串。
这是我尝试过的代码:
@file_temp = Tempfile.new
@file_temp.binmode
@file_temp.write(model.activestorage_attribute.download)
Run Code Online (Sandbox Code Playgroud)
您也可以只调用ActiveStorage::Blob#open而不是重新发明轮子。
将 blob 下载到磁盘上的临时文件中。产生临时文件。
blob.open do |temp_file|
# do something with file...
end
# file is automatically closed and unlinked
Run Code Online (Sandbox Code Playgroud)
如果您真的想自己做,那么正确的方法是:
# Using `Tempfile.open with a block ensures that
# the file is closed and unlinked
Tempfile.open do |tempfile|
tempfile.binmode
# steams the file as chunks instead of loading it
# all into memory
model.activestorage_attribute.download do |chunk|
tempfile.write(chunk)
end
tempfile.rewind
# do something with tempfile
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4802 次 |
| 最近记录: |