簡體   English   中英

Carrierwave +文件上傳器

[英]Carrierwave + File Uploader

我正在試圖弄清楚如何正確設置Carrierwave以便能夠處理通過File Uploader發送的文件

文件上傳器

我已將fileuploader.jsfileuploader.css附加到我的資產管道(rails 3.2.0)並具有以下html:

<div id="file-uploader">       
    <noscript>          
        <p>Please enable JavaScript to use file uploader.</p>
        <!-- or put a simple form for upload here -->
    </noscript>         
</div>

和javascript:

$(document).ready(function(){

    var uploader = new qq.FileUploader({
      // pass the dom node (ex. $(selector)[0] for jQuery users)
      element: $('#file-uploader')[0],
      // path to server-side upload script
      action: '/photos',
      debug: true,
      params: {
        authenticity_token: "<%= form_authenticity_token.to_s %>"
      },
      onComplete: function(id, fileName, responseJSON){
        alert(responseJSON.toString());
      }
    });
});

當我選擇一個文件時,它會啟動腳本並調用我的應用程序。 這就是我不知道如何處理。

Carrierwave

我有一個Photo模型,它有mount_uploader :image, ImageUploader 因此在PhotoController我有:

def create
  io = AppSpecificStringIO.new(request.raw_post,params[:qqfile])

  @photo = Photo.new(:image => io)

  if @photo.save
    respond_to do |format|
      format.js  { render :josn => @photo.to_json(:methods => :success, :only => [:id, :image]) }
    end
  else
    respond_to do |format|
      format.js  { render :josn => {:success=>false} }
    end
  end
end

param只有qqfile ,它是文件名。 我發現request.raw_post有圖像的數據。 但我不知道它是什么格式(是64Bit還是不是)。 我一直試圖在這個問題上找到我可以找到的任何資源並嘗試任何東西。 Carrierwave wiki上的一個消息來源建議使用AppSpecificStringIO類。

class AppSpecificStringIO < StringIO
  attr_accessor :filepath

  def initialize(*args)
    super(*args[1..-1])
    @filepath = args[0]
  end

  def original_filename
    File.basename(filepath)
  end
end

在File Uploader的維基上有一個關於CarrierWave的建議 ,但我也無法解決任何問題。 就我所見, CarrierwaveStringIO並不存在。

我只想獲得一個將圖像上傳到Carrierwave的ajax解決方案。 感謝能幫助我的人。

其他鏈接供參考:

我正在使用rack-raw-upload gem

然后在我的控制器中我正在做以下事情:

def create
  if params[:qqfile]
    ## IE acts differently 
    file = params[:qqfile].is_a?(ActionDispatch::Http::UploadedFile) ? params[:qqfile] : params[:file]
    @attachment.asset = file
    xhr_create
  else
    super
  end
end

def xhr_create
  if @attachment.save
    render :json => { success: true }
  else
    render :json => @attachment.errors.to_json
  end
end

並在application.rb

 config.middleware.use 'Rack::RawUpload', :paths => ['/attachments']

這是一篇很好的文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM