简体   繁体   English

如何在rails上的ruby中使用jquery获取资源路径

[英]How to get assets path using jquery in ruby on rails

I am using file uploading in my ruby on rails application. 我在我的ruby on rails应用程序上使用文件上传。 And when the file is uploaded, I want to make the link for others so that they can also download that file. 当文件上传时,我想为其他人建立链接,以便他们也可以下载该文件。 I have a folder named job_attachments within the assets folder for the file attachments. 我在资产文件夹中有一个名为job_attachments的文件夹,用于文件附件。 I want to know how I can get the the path for job_attachments using jQuery. 我想知道如何使用jQuery获取job_attachments的路径。

I am doing something like this in my controller: 我在我的控制器中做了类似的事情:

  def uploadattachment
    if(params[:job][:uploaded_data])
        uploaded_io=params[:job][:uploaded_data]
        File.open(Rails.root.join('app/assets', 'job_attachments', uploaded_io.original_filename), 'wb') do |f| 
              f.write(uploaded_io.read) 
        end

    respond_to do |format|
      format.json {render :layout=>false , :json => uploaded_io.original_filename}      
    end
end

end 结束

You probably don't want to put uploaded content into your assets folder. 您可能不希望将上传的内容放入资源文件夹中。 Assets are for things that you create that are part of your application. 资产适用于创建的属于您的应用程序的内容。 Additionally, app/assets isn't directly accessible by clients. 此外,客户无法直接访问app/assets I assume you want people to be able to download these files? 我假设你希望人们能够下载这些文件?

Create another folder under public ("uploads", perhaps), and put your files there. 在public下创建另一个文件夹(可能是“uploads”),然后将文件放在那里。

To get the path in jQuery, just return the path from your controller when the file is uploaded. 要在jQuery中获取路径,只需在上载文件时从控制器返回路径。 You probably want to turn a hash, rather than a string, since that's a little easier to deal with in jQuery. 您可能希望转换哈希值而不是字符串,因为在jQuery中处理它更容易。

def uploadattachment
  if(params[:job][:uploaded_data])
      uploaded_io=params[:job][:uploaded_data]
      File.open(Rails.root.join('public', 'uploads', 'job_attachments', uploaded_io.original_filename), 'wb') do |f| 
            f.write(uploaded_io.read) 
      end

      respond_to do |format|
        format.json {render :layout=>false , :json => {:path => File.join('uploads', uploaded_io.original_filename}}      
      end
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM