Paperclip and xhr.sendAsBinary

后端 未结 1 1938
我寻月下人不归
我寻月下人不归 2021-01-02 22:56

I use paperclip to add a file to my model.

I want to use the new feature of firefox 3.6, xhr.sendAsBinary, to send a file with an ajax request.

1条回答
  •  迷失自我
    2021-01-02 23:29

    I finally made it work!

    my javascript sending file looks like this

     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);
         }
     }
    

    now Paperclip handles the file as a normal input file

    0 讨论(0)
提交回复
热议问题