我有一个带有拖放区域的表单和一个可选的“选择文件”按钮。
<form method="post" action="upload.php" enctype="multipart/form-data" novalidate class="box">
(.....)
<input type="file" name="files" id="file" class="box__file" />
(.....)
</form>
检查md5哈希值后,应使用ajax上传文件。看起来像这样:
$( '.box' ).each( function()
{
var $form = $( this ),
$input = $form.find( 'input[type="file"]' ),
$label = $form.find( 'label' ),
$errorMsg = $form.find( '.box__error span' ),
$restart = $form.find( '.box__restart' ),
droppedFiles = false,
showFiles = function( files )
{
$label.text( files.length > 1 ? ( $input.attr( 'data-multiple-caption' ) || '' ).replace( '{count}', files.length ) : files[ 0 ].name );
};
// letting the server side to know we are going to make an Ajax request
$form.append( '<input type="hidden" name="ajax" value="1" />' );
// automatically submit the form on file select
$input.on( 'change', function( e )
{
showFiles( e.target.files );
$form.trigger( 'submit' );
});
// drag&drop files if the feature is available
if( isAdvancedUpload )
{
$form
.addClass( 'has-advanced-upload' ) // letting the CSS part to know drag&drop is supported by the browser
.on( 'drag dragstart dragend dragover dragenter dragleave drop', function( e )
{
// preventing the unwanted behaviours
e.preventDefault();
e.stopPropagation();
})
.on( 'dragover dragenter', function() //
{
$form.addClass( 'is-dragover' );
})
.on( 'dragleave dragend drop', function()
{
$form.removeClass( 'is-dragover' );
})
.on( 'drop', function( e )
{
droppedFiles = e.originalEvent.dataTransfer.files; // the files that were dropped
$form.trigger( 'submit' ); // automatically submit the form on file drop
});
}
// if the form was submitted
$form.on( 'submit', function( e ) {
// preventing the duplicate submissions if the current one is in progress
if( $form.hasClass( 'is-uploading' ) ) return false;
$form.addClass( 'is-uploading' ).removeClass( 'is-error' );
if( isAdvancedUpload ) {
var ajaxData = new FormData( $form.get( 0 ) );
var input = document.getElementById('file'); // <<<< PROBLEM
if (!input.files.length) { return; }
var file = input.files[0];
var bufferSize = Math.pow(1024, 2) * 50;
calculateMD5Hash(file, bufferSize).then((result) => {
if(result) { .......
如果我使用“选择文件”按钮上传,则它可以完美运行。
但是拖放功能会通过.on('drop',function(e),像应有的那样触发提交按钮,但是它会停在
var input = document.getElementById('file');
if (!input.files.length) { return; }
因为无法访问该文件。因此,我可能需要通过拖放功能将拖放的文件传输到输入字段,以某种方式对其进行访问。 你能帮助我吗??