【问题标题】:When I download Excel files, strange files are stored当我下载 Excel 文件时,会存储奇怪的文件
【发布时间】:2021-07-06 02:37:06
【问题描述】:

我想下载已上传的.zip、.xlsm、xlsx、pdf……等已上传的文件,我想最终将它们压缩成一个zip文件以供下载。

但是,如果上传的文件没有被压缩,它们将被下载,其中存储着奇怪的文件。

在这种情况下,.xlsm

源代码

class DownloadZipsController < ::ApplicationController

      def index
        file_name = "#{Time.current.strftime("%Y%m%d_%H%M%S")}.zip"
        zip_file = Tempfile.new(file_name)

        Zip.unicode_names = true
        Zip::OutputStream.open(zip_file.path) do |zip|
          params[:product_ids].each do |product_id|
            product = Product.find(product_id)
            zip.put_next_entry("output.zip")
            zip.print Net::HTTP.get URI.parse(product.submit_zip_file.url)
          end
        end

        send_file zip_file.path,
              type: "application/zip",
              disposition: "attachment",
              filename: file_name

        zip_file.close

      rescue => e
        logger.debug e.backtrace
        redirect_to request.referer, alert: e.message
      end

    end

上传的文件存储在 AWS S3 中。

有没有办法解决这个问题?

【问题讨论】:

  • 您确实应该将此代码移出控制器并放入可以单独测试的单独服务对象中。

标签: ruby-on-rails ruby rubyzip


【解决方案1】:

.xlsm.xlsx.docx 等 Office 文档实际上是 zip 文件,其中包含作为 xml 文件的文档以及其他资源。

如果您将其解释为 zip 文件并解压缩,您在屏幕截图中显示的文件树会显示一个此类文档的内容。

似乎在您的代码中的某个地方,您已将文档文件检测为 zip 文件并将其解释为导致其内容被解压缩。

这在您发布的代码中并不明显,因此我假设您在其他地方对 zip 文件进行了一些额外的处理(例如下载现有文件的功能,然后这些文件可能会以错误的内容类型发送到浏览器,即application/zip 而不是application/vnd.ms-excel.sheet.macroEnabled.12)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多