如何使用自定义上传文件?
<%= f.file_field :image, class: 'inputfile' %>
<label for="image">Choose an image</label>
我想用“选择文件”放置“选择图像”
答案 0 :(得分:1)
你的javascript缺少获取所选文件名的逻辑作为教程:
var fileName = e.target.value.split( '\\' ).pop();
因此,您的javascript将更新为:
input.addEventListener( 'change', function( e ) {
var inspiration_image = e.target.value.split( '\\' ).pop();
if( inspiration_image ) {
label.querySelector( 'span' ).innerHTML = inspiration_image;
} else {
label.innerHTML = labelVal;
}
});
使用完整代码进行更新
<%= file_field_tag :image, class: 'inputfile' %>
<label for="inspiration_image">Choose a file</label>
<script>
var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input ) {
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e ) {
var fileName = '';
if( this.files && this.files.length > 1 ) {
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
} else {
fileName = e.target.value.split( '\\' ).pop();
}
if( fileName ) {
label.querySelector( 'span' ).innerHTML = fileName;
} else {
label.innerHTML = labelVal;
}
});
});
</script>