在 rails 上将 .txt 文件转换为 .xml ruby
Converting .txt file to .xml ruby on rails
我有一个自定义文件类型 (.map),我正在从 Gzip 文件中解压缩,然后写入一个新文件,以便将其传递到 Paperclip 并上传到 s3。我的问题是类型应该是 xml,而它保存为文本文档而不是所有 xml 格式正确。我需要一种方法将其转换为 xml 类型,然后在传递之前将其另存为新的 File 对象。
到目前为止,这是我的代码:
Zlib::GzipReader.open(f.tempfile) do |gz|
puts gz.orig_name
@tmp = File.new(gz.orig_name, "w+")
while chunk = gz.read(16*1024) do
@tmp.write(chunk)
end
end
reader = @tmp.read
s = location.posts.create!(
subject: @email.subject,
from: @email.from[:email],
mapfile: @tmp)
}
理想情况下,我会将 mapfile 传递给 xml 类型的文件,但现在它似乎是文本
更新:
所以现在我已经设置了我的 post.rb 来执行此操作,并向 post 添加了一个包含原始文件名的名称属性:
has_attached_file :mapfile,
:preserve_files => "true",
:path =>
':rails_root/non-public/system/:id/:basename.:extension',
:url => '/:class/:id/mapfiles',
:s3_headers => lambda { |attachment| {'Content-Disposition' => "attachment; filename = #{attachment.name}"}}
这很完美!
听起来你在谈论“内容类型”。当你将文件保存到文件系统时,你不能设置这个:系统将根据文件扩展名决定使用什么,如果它是一个文本文件,可能还通过分析内容来决定使用什么。
但是,您可以在将文件提供给某人的浏览器以及将文件上传到 S3 时设置内容类型。后者请看这里Setting the Content-Type in direct to S3 upload using Rails and jQuery File Upload
我有一个自定义文件类型 (.map),我正在从 Gzip 文件中解压缩,然后写入一个新文件,以便将其传递到 Paperclip 并上传到 s3。我的问题是类型应该是 xml,而它保存为文本文档而不是所有 xml 格式正确。我需要一种方法将其转换为 xml 类型,然后在传递之前将其另存为新的 File 对象。
到目前为止,这是我的代码:
Zlib::GzipReader.open(f.tempfile) do |gz|
puts gz.orig_name
@tmp = File.new(gz.orig_name, "w+")
while chunk = gz.read(16*1024) do
@tmp.write(chunk)
end
end
reader = @tmp.read
s = location.posts.create!(
subject: @email.subject,
from: @email.from[:email],
mapfile: @tmp)
}
理想情况下,我会将 mapfile 传递给 xml 类型的文件,但现在它似乎是文本
更新:
所以现在我已经设置了我的 post.rb 来执行此操作,并向 post 添加了一个包含原始文件名的名称属性:
has_attached_file :mapfile,
:preserve_files => "true",
:path =>
':rails_root/non-public/system/:id/:basename.:extension',
:url => '/:class/:id/mapfiles',
:s3_headers => lambda { |attachment| {'Content-Disposition' => "attachment; filename = #{attachment.name}"}}
这很完美!
听起来你在谈论“内容类型”。当你将文件保存到文件系统时,你不能设置这个:系统将根据文件扩展名决定使用什么,如果它是一个文本文件,可能还通过分析内容来决定使用什么。
但是,您可以在将文件提供给某人的浏览器以及将文件上传到 S3 时设置内容类型。后者请看这里Setting the Content-Type in direct to S3 upload using Rails and jQuery File Upload