Fill the value of input file using jquery

elements with type="file" let the user choose one or more files from their device storage. Once chosen, the files can be uploaded khổng lồ a VPS using size submission, or manipulated using JavaScript code & the File API.

Bạn đang xem: Fill the value of input file using jquery

The source for this interactive example is stored in a GitHub repository. If you"d like lớn contribute to lớn the interactive sầu examples project, please clone và skết thúc us a pull request.

Value A DOMString representing the path to the selected file.
Events change và input
Supported comtháng attributes required
Additional Attributes accept, capture, files, multiple
IDL attributes files & value
DOM interface



Properties that apply only lớn elements of type file

Methods select()

A tệp tin input"s value attribute contains a DOMString that represents the path to lớn the selected file(s). If the user selected multiple files, the value represents the first tệp tin in the list of files they selected. The other files can be identified using the input"s HTMLInputElement.files property.

In addition to lớn the common attributes shared by all elements, inputs of type tệp tin also support the following attributes:

Attribute Description
accept One or more unique tệp tin type specifiers describing file types lớn allow
capture What source lớn use for capturing image or video data
files A FileList listing the chosen files
multiple A Boolean which, if present, indicates that the user may choose more than one file

The accept attribute value is a string that defines the file types the file input đầu vào should accept. This string is a comma-separated list of quality file type specifiers. Because a given tệp tin type may be identified in more than one manner, it"s useful to provide a thorough set of type specifiers when you need files of a given format.

For instance, there are a number of ways Microsoft Word files can be identified, so a site that accepts Word files might use an lượt thích this:

đầu vào type="file" id="docpicker" accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
The capture attribute value is a string that specifies which camera lớn use for capture of image or video data, if the accept attribute indicates that the input đầu vào should be of one of those types. A value of user indicates that the user-facing camera and/or microphone should be used. A value of environment specifies that the outward-facing camera and/or microphone should be used. If this attribute is missing, the user agent is miễn phí to lớn decide on its own what khổng lồ vì chưng. If the requested facing mode isn"t available, the user agent may fall bachồng lớn its preferred default mode.

Note: capture was previously a Boolean attribute which, if present, requested that the device"s truyền thông capture device(s) such as camera or microphone be used instead of requesting a file input.

A FileList object that lists every selected tệp tin. This danh mục has no more than one thành viên unless the multiple attribute is specified.

When the multiple Boolean attribute is specified, the file đầu vào allows the user khổng lồ select more than one file.

In addition lớn the attributes listed above sầu, the following non-standard attributes are available on some browsers. You should try to avoid using them when possible, since doing so will limit the ability of your code to function in browsers that don"t implement them.

Attribute Description
webkitdirectory A Boolean indicating whether or not lớn only allow the user khổng lồ choose a directory (or directories, if multiple is also present)

The Boolean webkitdirectory attribute, if present, indicates that only directories should be available to lớn be selected by the user in the file picker interface. See HTMLInputElement.webkitdirectory for additional details & examples.

Note: Though originally implemented only for WebKit-based browsers, webkitdirectory is also usable in Microsoft Edge as well as Firefox 50 và later. However, even though it has relatively broad tư vấn, it is still not standard and should not be used unless you have no alternative.

A unique tệp tin type specifier is a string that describes a type of tệp tin that may be selected by the user in an element of type file. Each chất lượng tệp tin type specifier may take one of the following forms:

A valid case-insensitive filename extension, starting with a period (".") character. For example: .jpg, .pdf, or .doc. A valid MIME type string, with no extensions. The string audio/* meaning "any audio file". The string video/* meaning "any đoạn Clip file". The string image/* meaning "any image file".

The accept attribute takes as its value a string containing one or more of these unique file type specifiers, separated by commas. For example, a tệp tin picker that needs content that can be presented as an image, including both standard image formats và PDF files, might look lượt thích this:

input đầu vào type="file" accept="image/*,.pdf">

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 lớn choose a file.

Including the multiple attribute, as shown above sầu, 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 platkhung allows (e.g. by holding down Shift or Control, and then clicking). If you only want the user to lớn choose a single file per , omit the multiple attribute.

The selected files" are returned by the element"s HTMLInputElement.files property, which is a FileList object containing a list of File objects. The FileList behaves lượt thích an array, so you can kiểm tra its length property khổng lồ get the number of selected files.

Each File object contains the following information:

name The file"s name. lastModified 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). lastModifiedDate This deprecated API should no longer be used, but will probably still work.

A Date object representing the date và time at which the tệp tin was last modified. This is deprecated and should not be used. Use lastModified instead. kích cỡ The size of the file in bytes. type The file"s MIME type. webkitRelativePath This API has not been standardized. A string specifying the file"s path relative sầu to lớn 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.

Xem thêm: Hướng Dẫn Tải Game Siêu Nhân Gao, Tải Game Siêu Nhân Gao 3D

Note: You can phối as well as get the value of HTMLInputElement.files in all modern browsers; this was most recently added to Firefox, in version 57 (see bug1384030).

Often you won"t want the user lớn be able to lớn piông xã any arbitrary type of file; instead, you often want them to select files of a specific type or types. For example, if your tệp tin input lets users upload a protệp tin picture, you probably want them khổng lồ select web-compatible image formats, such as JPEG or PNG.

Acceptable tệp tin types can be specified with the accept attribute, which takes a comma-separated menu of allowed tệp tin 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 tệp tin with an image/* MIME type. (Many điện thoại 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 at a more complete example:

It may look similar, but if you try selecting a tệp tin with this input đầu vào, 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 và operating systems).


The accept attribute doesn"t validate the types of the selected files; it provides hints for browsers lớn guide users towards selecting the correct tệp tin types. It is still possible (in most cases) for users khổng lồ toggle an option in the file chooser that makes it possible lớn override this & select any file they wish, và then choose incorrect tệp tin types.

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

You cannot mix the value of a tệp tin picker from a script — doing something like the following has no effect:

const input = document.querySelector("input");input đầu vào.value = "foo";
In this example, we"ll present a slightly more advanced file chooser that takes advantage of the tệp tin information available in the HTMLInputElement.files property, as well as showing off a few clever tricks.

Note: 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:

Next, let"s walk through the JavaScript.

In the first lines of script, we get references khổng lồ the size input đầu vào itself, và the
element with the class of .preview. Next, we hide the element — we vị this because file inputs tkết thúc lớn be ugly, difficult to style, and inconsistent in their kiến thiết across browsers. You can activate the input đầu vào element by clicking its , so it is better khổng lồ visually hide the input đầu vào and style the label lượt thích a button, so the user will know khổng lồ interact with it if they want to lớn upload files.

const input = document.querySelector("input");const previews = document.querySelector(".preview"); = 0;
Note: opathành phố is used to hide the tệp tin input instead of visibility: hidden or display: none, because assistive sầu giải pháp công nghệ interprets the latter two styles lớn mean the file đầu vào isn"t interactive.

Next, we add an event listener to lớn the input khổng lồ listen for changes lớn its selected value changes (in this case, when files are selected). The sự kiện listener invokes our custom updateImageDisplay() function.

input đầu vào.addEventListener("change", updateImageDisplay);Whenever the updateImageDisplay() function is invoked, we:

Chechồng khổng lồ see if no files were selected, by checking if curFiles.length is equal to 0. If so, print a message into the previews
stating that no files have been selected. If files have been selected, we loop through each one, printing information about it into lớn the pđánh giá
. Things to lớn note here: We use the custom validFileType() function lớn kiểm tra whether the tệp tin is of the correct type (e.g. the image types specified in the accept attribute). If it is, we: Print out its name và file form size into lớn a các mục thắng lợi inside the previous
(obtained from tệp and tệp tin.size). The custom returnFileSize() function returns a nicely-formatted version of the kích thước in bytes/KB/MB (by mặc định the browser reports the kích thước in absolute bytes). If the tệp tin type is invalid, we display a message inside a list thành quả telling the user that they need to lớn select a different tệp tin type.

function updateImageDisplay() while(pReviews.firstChild) pReview.removeChild(pReview.firstChild); const curFiles = input đầu vào.files; if(curFiles.length === 0) const para = document.createElement("p"); para.textContent = "No files currently selected for upload"; previews.appendChild(para); else const list = document.createElement("ol"); pReview.appendChild(list); for(const tệp tin of curFiles) const listItem = document.createElement("li"); const para = document.createElement("p"); if(validFileType(file)) para.textContent = `File name $tệp, tệp tin size $returnFileSize(tệp tin.size).`; const image = document.createElement("img"); image.src = URL.createObjectURL(file); listItem.appendChild(image); listItem.appendChild(para); else para.textContent = `File name $ Not a valid file type. Update your selection.`; listItem.appendChild(para); danh mục.appendChild(listItem); The custom validFileType() function takes a File object as a parameter, then uses Array.prototype.includes() to lớn check if any value in the fileTypes matches the file"s type property. If a match is found, the function returns true. If no match is found, it returns false.

// fileTypes = < "image/apng", "image/bmp", "image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/svg+xml", "image/tiff", "image/webp", "image/x-icon">;function validFileType(file) return fileTypes.includes(file.type);The returnFileSize() function takes a number (of bytes, taken from the current file"s form size property), & turns it inlớn a nicely formatted kích cỡ in bytes/KB/MB.

function returnFileSize(number) if(number 1024) return number + "bytes"; else if(number >= 1024 &và number 1048576) return (number/1024).toFixed(1) + "KB"; else if(number >= 1048576) return (number/1048576).toFixed(1) + "MB"; The example looks lượt thích this; have a play:

Specification Status Comment
HTML Living StandardThe definition of "" in that specification. Living Standard Initial definition
HTML 5.1The definition of "" in that specification. Recommendation Initial definition
HTML Media CaptureThe definition of "capture attribute" in that specification. Recommendation initial capture attribute

Browser compatibility

BCD tables only load in the browser

See also

Related Topics
types HTML Elements A B C D E F G H I J K L M N O Phường. Q R S