我正在学习前端,并试图实现文件拖放。我读了指南和文档,并试图实现这一点,但当我拖动文件的事件工程,它没有文件在数据传输。
超文本标记语言:
<form
id='upload-profile-avatar'
class='form form-upload-avatar flex-column-centered flex-centered gap-10'
action='/change_avatar'
method='POST'
enctype='multipart/form-data'
>
<div class='flex-column-centered flex-centered gap-5 upload-avatar-modal__image'><img
class='upload-avatar-modal__picture'
src='/img/upload.png'
alt='upload image'
/>
<span class='upload-avatar-modal-image__message'>Drag Here</span></div>
<div class='flex-centered upload-avatar-modal__alternative'><span
class='font-size-14 upload-avatar-modal-image__message'
>or</span></div>
<div class='form__input form__input-upload-avatar'>
<button
type='button'
data-action='choose'
class='btn btn-upload-avatar padding-5-10 border-radius-5 font-size-16 font-weight-bold'
form='upload-avatar'
>
<span>Upload<input
type='file'
data-name='upload-avatar'
accept='image/jpeg, image/png'
class='input input-upload-avatar'
name='user-avatar'
/></span>
</button>
</div>
<div class='upload-avatar-modal__avatar-preview'><img
class='avatar border-radius-10 avatar-preview__image'
src=''
alt='avatar-preview'
/><div class='flex-centered upload-avatar-modal__undo'><button
class='stratch-layout flex-centered border-radius-5 btn btn-revert-change-avatar'
><img src='/svg/close.svg' alt='undo-change-avatar' /></button></div></div>
</form>
字符串
我把文件放在这个表单上。JS:
const dropAvatarHandler = (e) => {
e.preventDefault();
console.log(e);
const file = e.dataTransfer?.files[0];
if(!file)
return;
e.target.querySelector('.input-upload-avatar').files[0]=file;
//function which does something with files
previewAvatar(e);
}
const dragoverAvatarHandler = (e) => {
e.preventDefault();
}
document.querySelector('.form-upload-avatar').addEventListener('dragover',dragoverAvatarHandler);
document.querySelector('.form-upload-avatar').addEventListener('drop',dropAvatarHandler);
型
console.log告诉我没有文件,但我删除了一个文件。根据指南和文档,它必须工作,但我没有看到问题。
我试了一些指南,但它仍然不工作。
1条答案
按热度按时间wtzytmuj1#
将
DataTransfer
对象中的整个FileList
对象分配给输入对象,而不是将单个文件附加到输入的FileList
。个字符