2010-02-21 86 views
6

我使用回形針將文件添加到我的模型。回形針和xhr.sendAsBinary

我想使用firefox 3.6的新功能,xhr.sendAsBinary,發送帶有ajax請求的文件。

這裏是我建立了我的請求:

var xhr = new XMLHttpRequest(); 


xhr.open("POST", "/photos?authenticity_token=" + token 
         + "&photo[name]=" + img.name 
         + "&photo[size]=" + img.size); 

xhr.overrideMimeType('text/plain; charset=x-user-defined-binary'); 
xhr.sendAsBinary(bin); 

namesize保存在我的模式沒有問題,但文件本身不被逮住回形針。

我的模型

class Photo < ActiveRecord::Base 
    has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" } 
end 

遷移

def self.up 
    add_column :photos, :photo_file_name,  :string 
    add_column :photos, :photo_content_type, :string 
    add_column :photos, :photo_file_size,  :integer 
    add_column :photos, :photo_updated_at, :datetime 
end 

和我的控制器

# POST /photos 
    # POST /photos.xml 
    def create 
    @photo = Photo.new(params[:photo]) 

    respond_to do |format| 
     if @photo.save 
     format.html { redirect_to(@photo, :notice => 'Photo was successfully created.') } 
     format.xml { render :xml => @photo, :status => :created, :location => @photo } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @photo.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

不知道如何解決這個問題呢?

謝謝

+0

那你的控制? – 2010-02-21 18:37:32

+0

這是,謝謝 – denisjacquemin 2010-02-21 19:08:36

回答

4

我終於成功了!

我的JavaScript發送文件看起來像這樣

send : function() { 
    try { 
     var xhr = new XMLHttpRequest; 
     //var url = this.form.action; 
     var url = '/photos'; 

     var boundary = this.generateBoundary(); 
     var contentType = "multipart/form-data; boundary=" + boundary; 

     this.filesToUpload.forEach(function(file, index, all) { 

      xhr.open("POST", url, true); 
      xhr.setRequestHeader("Content-Type", contentType); 

      for (var header in this.headers) { 
       xhr.setRequestHeader(header, headers[header]); 
      } 


      var CRLF = "\r\n"; 
      var request = "--" + boundary + CRLF; 

      request += 'Content-Disposition: form-data; '; 
      request += 'name="' + 'photo[name]' + '"' + CRLF + CRLF; 
      request += file.name + CRLF; 

      request += "--" + boundary + CRLF; 

      request += 'Content-Disposition: form-data; '; 
      request += 'name="' + 'photo[photo]' + '"; '; 
      request += 'filename="'+ file.fileName + '"' + CRLF; 

      request += "Content-Type: application/octet-stream" + CRLF + CRLF; 
      request += file.value + CRLF; 
      request+= "--" + boundary + "--" + CRLF; 

      xhr.sendAsBinary(request); 
     }); 
     // finally send the request as binary data 
     //xhr.sendAsBinary(this.buildMessage(this.filesToUpload, boundary)); 
    } catch(e) { 
     alert('send Error: ' + e); 
    } 
} 

現在回形針處理文件作爲一個正常的input file