将Dropzone file.fullPath发送到Rails控制器

时间:2015-04-02 22:11:55

标签: javascript jquery ruby-on-rails ajax

我正在尝试提取从将文件夹放入Chrome中的Dropzone上传的文件的完整路径。正在正确传输文件上载和所有其他元数据。我只想传递正在上传的文件的完整路径。

我已经尝试了很多来解决这个问题,但对Javascript来说还是比较新的。这些是我的资源:

Get uploaded file from Dropzone

Passing JQuery Datepicker Data to Rails Controller

Passing the variables from from jquery to rails controller

How to pass variables from AJAX form into controller?

Dropzone.js and full path for each file没有回复

这些是我的尝试:

上传new.html.erb

<%= form_for([@parent, @upload], method: :post, html: { multipart: true, class: "dropzone", id: "upload-dropzone"}) do |f| %>

  <% if @upload.errors.any? %>
    <ul>
      <% @upload.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  <% end %>
  <%= hidden_field_tag :full_path %>
  <%= javascript_tag do %>
    window.parent = '<%= @parent.id %>';
  <% end %>

<% end %>

的application.js

//= require jquery
//= require jquery_ujs
//= require dropzone
//= require turbolinks
//= require_tree .
// Dropzone.autoDiscover = false;

// $(document).ready(function(){
//   var myDropzone = Dropzone.getElementById("upload-dropzone");
//   new Dropzone(myDropzone);
//   myDropzone.on("sending", function(file, xhr, formData){
//     formData.append('full_path', file.fullPath);
//   })
//   console.log(file.fullPath);
// })

// var myDropzone = new Dropzone("#upload-dropzone");
// document.querySelector("#upload-dropzone").classList.add("dropzone");
// var myDropzone = document.getElementById("upload-dropzone");
// Dropzone.myDropzone.on("sending", function(file, xhr, formData){
//   formData.append('full_path', file.fullPath);
// })

Dropzone.options.uploadDropzone = {

  accept: function(file, done){
    var fullPath = { full_path: file.fullPath };
    $.ajax({
      type: "POST",
      data: { full_path: fullPath.full_path }
    });
  done();
  }
}

application.js还尝试从jQuery Dropzone元素中提取fullPath。在未注释的函数中,我可以使用以下命令访问javascript控制台中的完整路径:

file.fullPath

我想在以下网址中访问:

上传控制器

def create
  @parent = Parent.find(params[:parent_id])
  # here is an attempt to create the upload with the file_path
  @upload = Upload.new(upload: params[:file], full_path: params[:full_path])
  if @upload.save!

    respond_to do |format|
      format.json{ render json: @upload }
    end
  end
end

的routes.rb

resources :parent do
  post 'uploads/new' => 'uploads#new'
end

1 个答案:

答案 0 :(得分:4)

这是有用的:

添加到 application.js

Dropzone.options.uploadDropzone = false;

添加到 upload.js

var myDropzone = new Dropzone("#upload-dropzone");
myDropzone.on("sending", function(file, xhr, formData) {
   formData.append("full_path", file.fullPath);
});