<input type="file" />
Using the element of type=”file” allows the user to select one or more elements to upload to the server by submitting a form, or to manipulate files through Javascript’s File API.
<label for="avatar">Choose a profile picture:</label>
<input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg">
Copy the code
Effect:
value
The value attribute of the file input contains a DOMString that represents the selected file path. If the user selects multiple files, value represents the first file in the list of files they selected. You can use the INPUT HTMLInputElement. Files attribute to identify other files.
Note
- If no file is selected, the value is an empty string
""
.- To prevent malware from guessing the file path, string to
C:\fakepath\
For the prefix.
Additional attributes
In addition to the public attributes shared by all elements, input of type File supports the following attributes:
attribute | instructions |
---|---|
accept | One or more unique file Type specifiers describe the file types allowed |
files | FileList The selected files are listed |
multiple | Boolean value, if present, indicating that the user can select multiple files |
accept
The Accept attribute is a string that defines the type of file that the file input should accept. This string is a comma-separated list of unique file type specifiers.
<input type="file" id="docpicker" accept=".doc,.docx">
Copy the code
files
FileList object Specifies each selected file. If the multiple attribute is not specified, the list has only one member.
multiple
When multiple is specified, file input allows the user to select multiple files.
Using file input
Basic example
<form method="post" enctype="multipart/form-data">
<div>
<label for="file">Choose file to upload</label>
<input type="file" id="file" name="file" multiple>
</div>
<div>
<button>Submit</button>
</div>
</form>
Copy the code
Contains the multiple attribute above, specifying that multiple files can be selected at once. Users can select multiple files from the file selector in any way their platform of choice allows (for example, hold down Shift or Control, then click). If you want the user to select only one file for each , omit the multiple attribute.
Gets information about the selected file
The selected File is returned with the HTMLInputElement. Files property, which is a FileList object containing a list of File objects. FileList behaves like an array, so you can check the length property to get the number of selected files.
Each File contains the following information:
name
The file name.
lastModified
A number specifying the date and time when the file was last modified, expressed in milliseconds since the UNIX era (midnight on January 1, 1970).
size
File size in bytes.
type
The MIME type of the file.
Restrict acceptable file types
In general, you don’t want the user to be able to select any type of file; Instead, you usually want them to select a specific type of file. For example, if your file input lets users upload profile pictures, you might want them to choose a Web-compatible image format, such as JPEG or PNG.
Acceptable file types can be specified with the Accept attribute, which is a comma-separated list of file extensions and MIME types. Some examples:
accept="image/png"
或accept=".png"
– PNG files are accepted.accept="image/png, image/jpeg"
或accept=".png, .jpg, .jpeg"
– PNG or JPEG files are acceptable.accept="image/*"
— Accept with oneImage / * MIME type
Any of the files. (Many mobile devices also allow users to take pictures with their camera while using it.)
Note
The Accept attribute does not validate the type of the selected file; It simply provides a prompt for the browser to guide the user to select the correct file type. Users can still (in most cases) toggle an option in the file selector to override this option and select any file they wish, and then select the incorrect file type. Therefore, you should ensure that the Accept attribute is supported by appropriate server-side validation.
Complex sample
<! DOCTYPEhtml>
<html>
<head>
<title>Complete file example</title>
<style>
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.8 rem;
height: auto;
}
form label:hover.form button:hover {
background-color: #2D5BA3;
color: white;
}
form label:active.form button:active {
background-color: #0D3F8F;
color: white;
}
</style>
</head>
<body>
<form>
<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 upload</p>
</div>
<div>
<button>Submit</button>
</div>
</form>
<script>
const input = document.querySelector('input');
const preview = document.querySelector('.preview');
input.style.opacity = 0;
input.addEventListener('change', updateImageDisplay);
function updateImageDisplay() {
while(preview.firstChild) {
preview.removeChild(preview.firstChild);
}
const curFiles = input.files;
if(curFiles.length === 0) {
const para = document.createElement('p');
para.textContent = 'No files currently selected for upload';
preview.appendChild(para);
} else {
const list = document.createElement('ol');
preview.appendChild(list);
for(const file of curFiles) {
const listItem = document.createElement('li');
const para = document.createElement('p');
if(validFileType(file)) {
para.textContent = `File name ${file.name}, file size ${returnFileSize(file.size)}. `;
const image = document.createElement('img');// Create the img tag
image.src = URL.createObjectURL(file);// Set the SRC of the img tag
listItem.appendChild(image);
listItem.appendChild(para);
} else {
para.textContent = `File name ${file.name}: Not a valid file type. Update your selection.`; listItem.appendChild(para); } list.appendChild(listItem); }}}// File format collection
const fileTypes = [
'image/apng'.'image/bmp'.'image/gif'.'image/jpeg'.'image/pjpeg'.'image/png'.'image/svg+xml'.'image/tiff'.'image/webp'.`image/x-icon`
];
// Verify the format of the uploaded file
function validFileType(file) {
return fileTypes.includes(file.type);
}
// Calculate the file size
function returnFileSize(number) {
const KB_SIZE = Math.pow(2.10);
const MB_SIZE = Math.pow(2.20);
if(number < KB_SIZE) {
return number + 'bytes';
} else if(number > KB_SIZE && number < MB_SIZE) {
return (number/KB_SIZE).toFixed(1) + 'KB';
} else if(number > MB_SIZE) {
return (number/MB_SIZE).toFixed(1) + 'MB'; }}</script>
</body>
</html>
Copy the code
supplement
URL.createObjectURL()
The url.createObjecturl () static method creates a DOMString with a URL representing the object given in the argument. The lifecycle of this URL and the Document binding in the window that created it. This new URL object represents the specified File object or Blob object.
Note
This feature is available in Web workers; this feature is not available in Service workers because it can cause memory leaks.
grammar
const objectURL = URL.createObjectURL(object);
Copy the code
parameter
Object A File object, Blob object, or MediaSource object used to create a URL.
The return value
A DOMString contains an object URL that can be used to specify the contents of the source object.
note
- Memory management
Every time the createObjectURL() method is called, a new URL object is created, even if you already created it with the same object as an argument. When these URL objects are no longer needed, each object must be freed by calling the url.revokeobjecturl () method.
Browsers automatically release documents when they are uninstalled, but for best performance and memory usage, you should actively release them when it is safe to do so.
Use the sample
- The back-end interface downloads files
// umi Request
const { run: clickExport } = useRequest(() = > exportRequest(params), {
manual: true.throttleInterval: 500.throwOnError: true.formatResult: (res) = > ({
data: typeof res === 'string' ? JSON.parse(res) : res,
}),
onSuccess: (data) = > {
// new Blob( array, options )
if (data.data) downLoadFile({ file: new Blob([data.data]), name: 'data. XLSX' });
},
onError: () = > {
message.info('Export failed'); }});Copy the code
/ * * *@description Download files@param File File flow; Name File name */
function downLoadFile({ file, name = 'download'}: { file: Blob; name? :string }) :void {
// Compatibility processing
if ('download' in document.createElement('a')) {
const link = document.createElement('a'); // Create a tag
link.style.display = 'none'; // Hide the A tag
link.href = URL.createObjectURL(file);// Set the href of the a tag
link.download = name; // Set a tag to Download (filename)
document.body.appendChild(link); // Insert the A tag
link.click(); / / triggers
URL.revokeObjectURL(link.href); // Release the URL object
document.body.removeChild(link);// Remove the a tag
} else{ navigator.msSaveBlob(file, name); }}Copy the code
reference
-
Use files in web applications
-
input type=”file”
-
URL.createObjectURL
-
Element Upload