简体   繁体   English

在ruby中获取图像的服务器路径

[英]getting the server path of the image in ruby

I am using file field control for upload image like below: 我正在使用file field控件来上传图像,如下所示:

<%= form_for(:ImageUpload, :html => { :id => "imageupload" }) do |f| %>
<table width="100%">
    <tr>
        <td align="left">
            <%= file_field( "upload", "datafile") %>
        </td>
    </tr>
</table>
<table width="92%">
            <tr>
               <td align="center">
                  <div class="button" style="margin-right:60px;">
                    <%= f.submit "Next", { :class => "buttonSearch"} %>
                  </div>
               </td>
            </tr>
</table>
<% end %>

controller page: 控制器页面:

  def create

    get_img_path = params[:upload][:datafile].path
    @blah = get_img_path

    render 'new'
  end

And I want to get sever path of the uploaded image and also want to change the server path of the image into this app/assets/upload because I want to store the uploaded image at this path app/assets/uploaded . 而且我想获取上载图像的服务器路径,并且还想将图像的服务器路径更改为此app/assets/upload因为我想将上载图像存储在此路径app/assets/uploaded Kindly suggest me, waiting for your reply. 请建议我,等待您的回复。 Thanks. 谢谢。

I'd personally use Paperclip, but if you want a totally "native" solution, why not try this recommendation : 我个人会使用Paperclip,但是如果您想要一个完全“本机”的解决方案,为什么不尝试以下建议

path = params[:file].path

Looking at your updates, it seems you're hitting an issue by only accessing the string element of the path. 查看更新,看来您仅通过访问路径的string元素遇到了问题。 The solution to that would be to translate it into a File object , which you'll then be able to load the path for 解决方案是将其转换为File对象 ,然后可以为该对象加载路径。

You can see this tutorial on how to go about it: 您可以查看此教程 ,了解如何进行:

#app/models/file.rb
Class File < ActiveRecord::Base
 def self.save(upload)
    name =  upload['datafile'].original_filename
    directory = "public/data"
    # create the file path
    path = File.join(directory, name)
    # write the file
    File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
  end
end

This is how you save the file; 这是保存文件的方式。 but if you wanted to get the path, you'd still use the .path method, except you need to do it on a File object 但是,如果您想获取路径,则仍然可以使用.path方法,除非您需要在File对象上进行操作

To do this, I looked at several resources , and found this : 为此,我查看了一些资源发现了

file = File.join(Rails.root, 'app', 'csv', 'names.csv')
file.path

I would recommend you to use Paperclip or Carrierwave gem to handle this. 我建议您使用PaperclipCarrierwave宝石来处理此问题。

Paperclip - Click Here 回形针- 单击此处

Carrierwave - Click Here 载波- 点击这里

To get the path you can do this 要获取路径,您可以执行此操作

file_path = params[:upload].blank? ? "" : params[:upload].path

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

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