【问题标题】:File name doesnt appear when uploaded上传时文件名不显示
【发布时间】:2020-08-19 05:52:15
【问题描述】:

我有一个表格,我有一个上传图片的部分,但是当我上传图片时,她的名字没有出现在标签上,我找到了一个代码使它部分工作,因为它不只显示图片名和是“C:\fakepath\图片名”,总之就是要图片名,谢谢!

表格:

<%= bootstrap_form_for(@var) do |f| %>
  <%= f.file_field :images, multiple: true, label: "Add an iamge" %>

显示“C:\fakepath\image name”的JS:

$(document).on('ready turbolinks:load', function() {
  $('.custom-file-input').change(function(){
    $('.custom-file-label').text(this.value);
  });
});

【问题讨论】:

  • .original_filename?对从参数收到的文件执行 .inspect。

标签: ruby-on-rails ruby bootstrap-4


【解决方案1】:

// When working with turbolinks stop moshing your code inside of turbolinks:load and ready handlers. 
// Write delegated event handlers instead which are idempotent by design.
$(document).on('change', '.custom-file-input', function(e) { 
  // split file path by back or forward slashes
  let path = this.value.split(/^.*[\\\/]/);
  this.labels[0].innerText = path.slice(-1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <label for="custom_file_input">Filename goes here</label>
  <input name="custom_file_input" id="custom_file_input" class="custom-file-input" type="file"/>
</form>

【讨论】:

  • 感谢您的帮助,但我还有一个问题,如果我添加多个文件,是否必须显示所有文件的名称?我该怎么做?
  • this.files 将为您提供可以迭代的文件列表。不过,这确实是一个单独的问题,应该这样问。 developer.mozilla.org/en-US/docs/Web/API/FileList
猜你喜欢
  • 2022-01-26
  • 1970-01-01
  • 2011-10-14
  • 2016-07-12
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多