require_dependency "educode_sales/application_controller" module EducodeSales class UploadFilesController < ApplicationController def index respond_to do |format| format.html do end format.json do @files = Attachment.where(description: "business", container_id:params[:business_id]) if params[:sort].present? && params[:sort][:field] @files = @files.order("#{params[:sort][:field]} #{params[:sort][:order]}") else @files = @files.order("created_on desc") end @files = @files.page(params[:page]).per(params[:limit]) end end end def create folder = edu_setting('attachment_folder') upload_file = params["file"] raise "未上传文件" unless upload_file save_path = File.join(folder) ext = file_ext(upload_file.original_filename) local_path, digest = file_save_to_local(save_path, upload_file.tempfile, ext) content_type = upload_file.content_type.presence || 'application/octet-stream' disk_filename = local_path[save_path.size + 1, local_path.size] @attachment = Attachment.where(disk_filename: disk_filename, author_id: @current_admin.id).first if @attachment.blank? @attachment = Attachment.new @attachment.filename = upload_file.original_filename @attachment.description = "business" @attachment.disk_filename = local_path[save_path.size + 1, local_path.size] @attachment.filesize = upload_file.tempfile.size @attachment.content_type = content_type @attachment.digest = digest @attachment.author_id = @current_admin.id @attachment.container_id = params[:business_id] @attachment.save! else logger.info "文件已存在,id = #{@attachment.id}, filename = #{@attachment.filename}" end render_success end def destroy folder = edu_setting('attachment_folder') file = Attachment.find(params[:id]) file.destroy File.delete(folder.to_s + '/' + file.disk_filename) if FileTest::exist?(folder.to_s + '/' + file.disk_filename) render_success end def download folder = edu_setting('attachment_folder') file = Attachment.find_by_id(params[:id]) raise "未找到文件" unless file send_file(folder.to_s + '/' + file.disk_filename, filename: file.title, stream: true, type: file.content_type.presence || 'application/octet-stream') end def edu_setting name EduSetting.get(name) end def file_ext(file_name) ext = '' exts = file_name.split(".") if exts.size > 1 ext = ".#{exts.last}" end ext end def file_save_to_local(save_path, temp_file, ext) unless Dir.exists?(save_path) FileUtils.mkdir_p(save_path) ##不成功这里会抛异常 end digest = md5_file(temp_file) digest = "#{digest}_#{(Time.now.to_f * 1000).to_i}" local_file_path = File.join(save_path, digest) + ext save_temp_file(temp_file, local_file_path) [local_file_path, digest] end def md5_file(temp_file) md5 = Digest::MD5.new temp_file.rewind while (buffer = temp_file.read(8192)) md5.update(buffer) end md5.hexdigest end def save_temp_file(temp_file, save_file_path) File.open(save_file_path, 'wb') do |f| temp_file.rewind while (buffer = temp_file.read(8192)) f.write(buffer) end end end end end