FE

HTML

Basic setup:

<form enctype="multipart/form-data">
  <input id="file" type="file" multiple="multiple" name="file" accept="...">
  <input type="submit" value="Upload">
</form>
Copy the code

The encType property of the Form

The encType property manages the MIME encoding of the form and has three properties:

value describe
application/x-www-form-urlencoded Encodes all characters before sending (default)
multipart/form-data No character encoding, used to specify special types of transmission data, such as MP3, JPG
text/plain Plain text transmission

Therefore, the multipart/form-data attribute is required to transfer complete file data.

Input

value

Saves the name of the file specified by the user.

type=”file”

Set input type to file.

multiple=”multiple”

Multiple options are available. Do not set this parameter to single.

accept=”…”

Sets the MIME_type of the optional file. Clicking the “Select File” button after setting will display files that match the set MIME_type by default (compatibility exists). The MIME types corresponding to specific file types can be searched. Here are the types I used:

The file type The MIME type
.txt text/plain
.pdf application/pdf
.doc application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.xls application/vnd.ms-excel
.ppt application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation

The effect

Too ugly to bear…

CSS

The default interface will be followed by a text area showing the file name after selecting the file button. Selecting the file button cannot be edited. I changed it by hiding the input box and setting an Lable label that triggers the file selection button when the user clicks on the Lable label.

<label for="file">Select the file</label>
Copy the code

The effect

JS

When submitting with FROM, the browser sends the contents of the selected file to the server rather than just the file name.

To be safe, the file-upload element does not allow HTML authors or JavaScript programmers to specify a default file name. The HTML value attribute is ignored, and for such elements, the value attribute is read-only, meaning that only the user can enter a filename. When a user selects or edits a file name, the file-upload element triggers an onchange event handle.

Using form references causes page refreshes and is a bad experience, so using AJAX for file uploads is a good choice. But it’s up to us to organize the content sent through POST requests.

FormData object

The FormData object lets you assemble a set of key/value pairs that send requests using XMLHttpRequest. It makes sending form data more flexible and convenient because it can be used independently of the form. If you set the encoding type of the form to multipart/form-data, the data transferred through FormData is in the same format as the data transferred through the form’s submit() method. – the MDN web docs

Create the FormData object

let formData = new FormData();
Copy the code

Add file fields to the instantiated object

let myFile = document.getElementById('file');
// myfile.file [0] is the first file (single), multiple files (multiple) are added in a loop
formData.append('myFile', myFile.files[0]);
Copy the code
console.log(myFile.files[0]);
Copy the code

The unit of size property is byte (b).

Add a custom field

formData.append('username'.'simmzl');
Copy the code

AJAX to send

let request = new XMLHttpRequest();
request.open("POST"."http://foo.com/foo.php");
request.send(formData);
Copy the code

Don’t use FromData objects

Without the FormData object, you need to serialize and submit the form via AJAX: Using nothing but XMLHttpRequest

PHP

receive

Global array $_FILES, the first argument is the form’s input name, the second subscript is “name”, “type”, “size”, “tmp_name” or” error”. You can make restrictions based on these attributes, such as limiting file size, file type, and so on.

value describe
name The file name
type The MIME type of the file
size File size in bytes
tmp_name The PHP received file is saved as a temporary file, which must be moved to save to the specified path
error 1-7Represents 7 different error categories as well0On behalf of success

Error: succeeded: 0(UPLOAD_ERR_OK) failed:

  1. The size of the configuration file to be uploaded exceeded. Procedure
  2. The size of the uploaded file exceeded the form setting
  3. The file part is uploaded
  4. No files were uploaded
  5. No temporary directory found
  6. File not writable
  7. File upload was interrupted due to PHP extension

validation

Uploaded_file (file) determines whether the specified file was uploaded via HTTP POST and returns a Boolean value.

This function can be used to ensure that malicious users cannot trick the script into accessing otherwise inaccessible files, such as /etc/passwd. This check is particularly important if the uploaded file has the potential to display its contents to the user or other users of the system.

save

The uploaded file is temporarily stored in tMP_name. Run move_uploaded_file(file, newLocation) to move the uploaded file to the specified path and return a Boolean value.

if( move_uploaded_file($tmp_name, $destination) ) {
  echo "File uploaded successfully";
}else{
  echo "File move failed";
}
Copy the code

delete

Delete a file using unlink(filepath). The parameter is the filepath.

Expand functionality

Of course, in addition to the four basic operations of receive, verify, save and delete, you can also add functions such as storing file paths into the database, generating file lists, etc., depending on your needs.

Originally published on blog.simmzl.cn