Как очистить input type file
Перейти к содержимому

Как очистить input type file

  • автор:

Как очистить input type file

Атрибут value элемента input содержит DOMString , который представляет путь к выбранным файлам. Если пользователь выбрал несколько файлов, value представляет первый файл из списка. Остальные файлы можно определить используя HTMLInputElement.files (en-US) свойство элемента input.

**Примечание:**1. Если выбрано несколько файлов, строка представляет собой первый выбранный файл. JavaScript предоставляет доступ к остальным файлам через свойство FileList . 2. Если не выбрано ни одного файла, .строка равна «» (пустая). 3. Строка начинается с C:\fakepath\ , для предотвращения определения файловой структуры пользователя вредоносным ПО.

Additional attributes

In addition to the common attributes shared by all elements, inputs of type file also support:

A FileList object that lists every selected file. This list has no more than one member unless the multiple attribute is specified.

Using file inputs

A basic example

form method="post" enctype="multipart/form-data"> div> label for="file">Choose file to uploadlabel> input type="file" id="file" name="file" multiple /> div> div> button>Submitbutton> div> form> 
div  margin-bottom: 10px; > 

This produces the following output:

Примечание: You can find this example on GitHub too — see the source code, and also see it running live.

Regardless of the user’s device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file.

Including the multiple attribute, as shown above, specifies that multiple files can be chosen at once. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down Shift or Control , and then clicking). If you only want the user to choose a single file per , omit the multiple attribute.

When the form is submitted, each selected file’s name will be added to URL parameters in the following fashion: ?file=file1.txt&file=file2.txt

Getting information on selected files

The selected files’ are returned by the element’s files property, which is a FileList object containing a list of File objects. The FileList behaves like an array, so you can check its length property to get the number of selected files.

Each File object contains the following information:

A number specifying the date and time at which the file was last modified, in milliseconds since the UNIX epoch (January 1, 1970 at midnight).

A Date object representing the date and time at which the file was last modified. This is deprecated and should not be used. Use lastModified instead.

The size of the file in bytes.

A string specifying the file’s path relative to the base directory selected in a directory picker (that is, a file picker in which the webkitdirectory attribute is set). This is non-standard and should be used with caution.

Примечание: You can set as well as get the value of HTMLInputElement.files in all modern browsers; this was most recently added to Firefox, in version 57 (see баг 1384030).

Limiting accepted file types

Often you won’t want the user to be able to pick any arbitrary type of file; instead, you often want them to select files of a specific type or types. For example, if your file input lets users upload a profile picture, you probably want them to select web-compatible image formats, such as JPEG or PNG (en-US) .

Acceptable file types can be specified with the accept attribute, which takes a comma-separated list of allowed file extensions or MIME types. Some examples:

  • accept=»image/png» or accept=».png» — Accepts PNG files.
  • accept=»image/png, image/jpeg» or accept=».png, .jpg, .jpeg» — Accept PNG or JPEG files.
  • accept=»image/*» — Accept any file with an image/* MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.)
  • accept=».doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document» — accept anything that smells like an MS Word document.

Let’s look like a more complete example:

form method="post" enctype="multipart/form-data"> div> label for="profile_pic">Choose file to uploadlabel> input type="file" id="profile_pic" name="profile_pic" accept=".jpg, .jpeg, .png" /> div> div> button>Submitbutton> div> form> 
div  margin-bottom: 10px; > 

This produces a similar-looking output to the previous example:

Примечание: You can find this example on GitHub too — see the source code, and also see it running live.

It may look similar, but if you try selecting a file with this input, you’ll see that the file picker only lets you select the file types specified in the accept value (the exact nature differs across browsers and operating systems).

Screenshot of a macOS file picker dialog. Files other than JPEG are grayed-out and unselectable.

The accept attribute doesn’t validate the types of the selected files; it simply provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.

Because of this, you should make sure that the accept attribute is backed up by appropriate server-side validation.

Examples

In this example, we’ll present a slightly more advanced file chooser that takes advantage of the file information available in the HTMLInputElement.files (en-US) property, as well as showing off a few clever tricks.

Примечание: You can see the complete source code for this example on GitHub — file-example.html (see it live also). We won’t explain the CSS; the JavaScript is the main focus.

First of all, let’s look at the HTML:

form method="post" enctype="multipart/form-data"> div> label for="image_uploads">Choose images to upload (PNG, JPG)label> input type="file" id="image_uploads" name="image_uploads" accept=".jpg, .jpeg, .png" multiple /> div> div class="preview"> p>No files currently selected for uploadp> div> div> button>Submitbutton> div> form> 
html  font-family: sans-serif; > form  width: 600px; background: #ccc; margin: 0 auto; padding: 20px; border: 1px solid black; > form ol  padding-left: 0; > form li, div > p  background: #eee; display: flex; justify-content: space-between; margin-bottom: 10px; list-style-type: none; border: 1px solid black; > form img  height: 64px; order: 1; > form p  line-height: 32px; padding-left: 10px; > form label, form button  background-color: #7f9ccb; padding: 5px 10px; border-radius: 5px; border: 1px ridge black; font-size: 0.8rem; height: auto; > form label:hover, form button:hover  background-color: #2d5ba3; color: white; > form label:active, form button:active  background-color: #0d3f8f; color: white; > 

This is similar to what we’ve seen before — nothing special to comment on.

Next, let’s walk through the JavaScript.

var input = document.querySelector("input"); var preview = document.querySelector(".preview"); input.style.opacity = 0; 

Примечание: opacity is used to hide the file input instead of visibility: hidden or display: none , because assistive technology interprets the latter two styles to mean the file input isn’t interactive.

Next, we add an event listener to the input to listen for changes to its selected value changes (in this case, when files are selected). The event listener invokes our custom updateImageDisplay() function.

.addEventListener("change", updateImageDisplay); 

Whenever the updateImageDisplay() function is invoked, we:

  • Use a while loop to empty the previous contents of the preview .
  • Grab the FileList object that contains the information on all the selected files, and store it in a variable called curFiles .
  • Check to see if no files were selected, by checking if curFiles.length is equal to 0. If so, print a message into the preview stating that no files have been selected.
  • If files have been selected, we loop through each one, printing information about it into the preview . Things to note here:
  • We use the custom validFileType() function to check whether the file is of the correct type (e.g. the image types specified in the accept attribute).
  • If it is, we:
    • Print out its name and file size into a list item inside the previous (obtained from curFiles[i].name and curFiles[i].size ). The custom returnFileSize() function returns a nicely-formatted version of the size in bytes/KB/MB (by default the browser reports the size in absolute bytes).
    • Generate a thumbnail preview of the image by calling window.URL.createObjectURL(curFiles[i]) and reducing the image size in the CSS, then insert that image into the list item too.
    function updateImageDisplay()  while (preview.firstChild)  preview.removeChild(preview.firstChild); > var curFiles = input.files; if (curFiles.length === 0)  var para = document.createElement("p"); para.textContent = "No files currently selected for upload"; preview.appendChild(para); > else  var list = document.createElement("ol"); preview.appendChild(list); for (var i = 0; i  curFiles.length; i++)  var listItem = document.createElement("li"); var para = document.createElement("p"); if (validFileType(curFiles[i]))  para.textContent = "File name " + curFiles[i].name + ", file size " + returnFileSize(curFiles[i].size) + "."; var image = document.createElement("img"); image.src = window.URL.createObjectURL(curFiles[i]); listItem.appendChild(image); listItem.appendChild(para); > else  para.textContent = "File name " + curFiles[i].name + ": Not a valid file type. Update your selection."; listItem.appendChild(para); > list.appendChild(listItem); > > > 

    The custom validFileType() function takes a File object as a parameter, then loops through the list of allowed file types, checking if any matches the file’s type property. If a match is found, the function returns true . If no match is found, it returns false .

    var fileTypes = ["image/jpeg", "image/pjpeg", "image/png"]; function validFileType(file)  for (var i = 0; i  fileTypes.length; i++)  if (file.type === fileTypes[i])  return true; > > return false; > 

    The returnFileSize() function takes a number (of bytes, taken from the current file’s size property), and turns it into a nicely formatted size in bytes/KB/MB.

    function returnFileSize(number)  if (number  1024)  return number + "bytes"; > else if (number > 1024 && number  1048576)  return (number / 1024).toFixed(1) + "KB"; > else if (number > 1048576)  return (number / 1048576).toFixed(1) + "MB"; > > 

    The example looks like this; have a play:

    Specifications

    Specification
    HTML Standard
    # file-upload-state-(type=file)

    Browser compatibility

    BCD tables only load in the browser

    See also

    • Using files from web applications — contains a number of other useful examples related to and the File API.

    Found a content problem with this page?

    • Edit the page on GitHub.
    • Report the content issue.
    • View the source on GitHub.

    This page was last modified on 11 окт. 2023 г. by MDN contributors.

    Your blueprint for a better internet.

    MDN

    Support

    • Product help
    • Report an issue

    Our communities

    Developers

    • Web Technologies
    • Learn Web Development
    • MDN Plus
    • Hacks Blog
    • Website Privacy Notice
    • Cookies
    • Legal
    • Community Participation Guidelines

    Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
    Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

    Курсы javascript

    Доброго времени суток. Нужно очистить заполненное поле ввода типа file.
    Пробовал $(«#my_file»).prop(«files», []) и странный метод document.getElementById(«my_file»).innerHTML = document.getElementById(«my_file»).innerHTML отсюда — ничего не работает(проверял только в последнем FF).
    Подскажите люди добрые, как это поле зачистить(не цепляя к нему отдельную форму, разумеется ).

    14.11.2014, 22:01
    что-то знаю
    Регистрация: 24.05.2009
    Сообщений: 5,176
    как вариант пересоздать элемент
    14.11.2014, 22:28
    Регистрация: 29.11.2011
    Сообщений: 3,924

    element.prop('value', null);

    __________________
    Чебурашка стал символом олимпийских игр. А чего достиг ты?
    Тишина — самый громкий звук

    14.11.2014, 23:10
    Регистрация: 11.09.2010
    Сообщений: 8,804
    __________________
    В личку только с интересными предложениями
    14.11.2014, 23:57
    Регистрация: 22.03.2012
    Сообщений: 3,744

    сам пример реализует один из вариантов того, про что ведёт речь devote

    15.11.2014, 00:31
    Регистрация: 09.11.2014
    Сообщений: 610
    Через input.value не получается?

        var but=document.querySelector("#but") var inp=document.querySelector("#inp") but.onclick=function()  

    Последний раз редактировалось krutoy, 15.11.2014 в 00:38 .
    15.11.2014, 02:02
    Интересующийся
    Регистрация: 14.12.2012
    Сообщений: 15

    Всем спасибо, в моём случае самым простым вариантом оказалось обернуть файлы в формы и очищать их $(«#form_my_file»)[0].reset();
    Сброс value нужно будет проверить, очень неочевидный вариант, учитывая отсутствие такого свойства у файлов .

    15.11.2014, 07:49
    Регистрация: 11.09.2010
    Сообщений: 8,804
    __________________
    В личку только с интересными предложениями
    15.11.2014, 08:24
    Регистрация: 09.11.2014
    Сообщений: 610
    15.11.2014, 09:33
    Регистрация: 22.03.2012
    Сообщений: 3,744

    input.value = «»; вполне кроссбраузерный вариант

        This can be used as follows: 

    The name of the file you picked is: (none)

Последний раз редактировалось bes, 15.11.2014 в 09:38 .

Страница 1 из 2 1 2 >

Как очистить input type file

С самого начала давайте приведем рабочий пример очистки поля выбора файла!

Пример: очистить поле ввода type=file

Для того, чтобы проверить работу примера очитки поля ввода вам потребуется:

Выбрать любой файл на вашем компьютере нажав кнопку "выбрать файл".

И второе - нажмите кнопку "очисти поле выбора файла"

очисти поле выбора файла

Пример кода очистки поля type=file

Для того, чтобы создать рабочий пример нам понадобится:

Тип file(поле для загрузки файлов)

Добавим ему id, чтобы вы могли к этому полю обратиться

Для кнопки нам нужен тег button.

Для того, чтобы отследить нажатие нам нужен onclick.

Обращаемся к нашему id с помощью getElementById

document.getElementById('example')

Ну и последнее добавляем value в js

Соберем весь код примера очитки поля файле:

javascript - очистка поля ввода type=file

Как вы знаете способов сделать onclick - 3 штуки. первый самый простой и короткий в смысле написания я рассмотрел выше.

Смысл тот же, но только onclick второй способ.

Для того, чтобы очистить поле выбора файл с помощью javascript - нам понадобится:

Опять поле type="file" + id изменим на "example1"

Снова кнопка "button" и добавим к ней "id", чтобы вы могли к ней обратиться.

И onclick вынесем в отдельный тег script, подробно останавливаться не буду. здесь все просто.

document.getElementById('id_button'). onclick=function()

Соберем второй пример очитки поля ввода файл.

Живой пример очистить поле выбора файла

Для того, чтобы протестировать работу очитки поля type="file" вам понадобится:

Очистить поле выбора файла.

очисти поле выбора файла

jQuery - очистим поля ввода type=file

И последним рассмотрим очищение поля файла с помощью jQuery.

Для этого нам понадобится.

Поле выбора файла:

Кнопка для очистки поля выбора файла:

jQuery - код очитки поля файла

Соберем весь код очистки поля файла в jQuery

Пример работы кода очистки поля файла в jQuery

Для того, чтобы протестировать работe кода очистки поля файла в jQuery вам нужно:

Очистить поле выбора файла

Удаление поля input type="file" с заданным именем файла

Если у меня есть несколько полей для прикрепления файлов input type="file", как можно удалить только тот input в котором был выбран файл с именем например "aaaa.jpg" , а остальные инпуты остались бы нетронутыми? Так вообще в принципе можно сделать? Или через jQuery например.
Спасибо

Лучшие ответы ( 1 )
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:

Удаление файлов из input type file
Можно как-то удалить файлы из инпута? Вот у меня пользователь выбрал 5 картинок, они появились у.

Удаление input type file при помещении туда фотографии
Всем привет! Появился вопрос: нужно убирать input type file Если фотография уже выбрана. Помогите .

Получить имя файла с input type=file
Всем привет. Есть форма и PHP код. Нужно в форме выбрать изображение с какой нибудь папки в ПК и.

Как проверить на наличие загружаемости файла?
Как проверить <input type='file'> на наличие загружаемости файла? У меня на странице несколько.

Отправка файла на сервер без использования input type=file
Всем привет. Подскажите пожалуйста, можно ли отправить файл на сервер без использования кнопки.

632 / 474 / 170
Регистрация: 26.05.2016
Сообщений: 2,622

SergTN, можно. Вам нужно простейшее условие использовать и удалять соответсвующий инпут. Файл, прикреплённый, будет вот тут

element.files[0];

Только вот если Вы удалите инпут, в который уже на клиенте «прикрепили» файл, к файлу будет невозможно обратиться.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *