taizo
taizo

Reputation: 77

When I download Excel files, strange files are stored

I want to download uploaded files such as .zip, .xlsm, xlsx, pdf... ..., etc., that have been uploaded, I want to eventually compress them into a zip file for download.

However, if the uploaded files are not zipped, they will be downloaded with strange files stored in them.

In this case, .xlsm

enter image description here

Source Code

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

Uploaded files are stored in AWS S3.

Is there any solution to this problem?

Upvotes: 1

Views: 490

Answers (1)

Holger Just
Holger Just

Reputation: 55758

Office Documents such as .xlsm, .xlsx, .docx, and others are in fact zip files containing the document as a xml file plus additional resources.

The file tree you have shown in your screenshot shows the content of one such document if you interpret it as a zip file and unpack.

It appears that somewhere in your code, you have detected the document file as a zip file and interpreted it as such which resulted in its contents to be unpacked.

This is not apparent from the code you have posted though, so I would assume that you have some additional handling of zip files somewhere else (such as a function to download existing files which may then be send with a wrong content type to the browser, i.e as an application/zip rather than application/vnd.ms-excel.sheet.macroEnabled.12).

Upvotes: 3

Related Questions