Upload Library
Category: FormThe upload module supports batch uploading in multiple formats, with direct cloud transmission to Amazon S3, Cloud Storage, Azure Blob Storage, OSS, COS, Kodo, UPYUN and other cloud services.
Preface
The native file upload control is frequently used, but its compatibility and aesthetics are relatively poor. Moreover, current frontend requirements for file uploads have become more complex, including drag-and-drop upload, multi-file upload, paste upload, upload previews, etc. Therefore, JavaScript plugins are ultimately required to implement file upload functionality.
This library has implemented common requirements for file uploads with the following features and characteristics:
- Supports single file and multiple files upload
- Supports both automatic and manual upload
- Can limit the number of uploadable files
- Can restrict file extensions and individual file size
- Counts selected files and uploaded files
- Automatically avoids duplicate file selection and upload
- Customizable pre-deletion dialog event
- Supports previews for images, audio, and video files (H5 format)
- Supports file download after successful upload
- Supports four list styles, with gallery recommended
- Supports drag-and-drop file upload
- Supports drag-and-drop folder upload
- Supports mixed drag-and-drop of files and folders
- Supports paste upload (local files not allowed)
- Supports dual validation: pre-upload JS validation and post-upload dynamic validation
- Customizable file type icons
Basic Usage
Apply the oc-upload
attribute to a div
or input
node to create a multi-file upload instance. However, the module ultimately needs to complete file uploads, so the url
parameter must be configured to point to the dynamic page address that receives the files.
The input
node can be a regular text input or file input.
- Output
- HTML
- PHP
-
Text Input
File Input
Other Nodes
-
-
//Test environment simulates cross-domain header("Access-Control-Allow-Origin: *"); //Define upload directory (simulated) $path = "filesDirectory/"; $path = "https://unpkg.com/orcares/image/"; //Define allowed file types $extArr = array("jpg", "png", "gif", "txt", "doc", "docx", "pdf", "xsl", "xslx","mp3","mp4"); //Define max file size (1MB) $maxSize = 1024 ** 3; //Get file extension function extend($file_name) { $extend = pathinfo($file_name); $extend = strtolower($extend["extension"]); return $extend; } //Get 13-digit timestamp to match file's lastModified function getTimestamp() { list($t1, $t2) = explode(' ', microtime()); return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000); } $timestamp = getTimestamp(); //Output result function echoResult($flag,$msg='Upload error!',$time,$url='',$name='') { $object = $flag?array('msg' => $msg, 'code' => 200, 'url' => $url, 'name' => $name,'time'=>$time):array('msg' => $msg, 'code' => 400,'time'=>$time); $result = json_encode($object); echo $result; } if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $file = $_FILES[array_shift(array_keys($_FILES))]; $name = $file['name']; $size = $file['size']; $tmp = $file['tmp_name']; //Random filename $ext = extend($name); $image_name = time() . rand(100, 999) . "." . $ext; //Server-side validation is necessary to prevent malicious uploads bypassing frontend validation if (empty($name)) { echoResult(false,'Please select a file!',$timestamp); exit; } if (!in_array($ext, $extArr)) { echoResult(false,'Invalid file format!',$timestamp); exit; } if ($size > $maxSize) { echoResult(false,'File size cannot exceed 1MB',$timestamp); exit; } if(!file_exists($path)){ //If path is incorrect (simulated) echoResult(true,'Simulated path upload success!',$timestamp,'https://unpkg.com/orcares/image/upload.jpg',$image_name); exit; }else{ //If all validations pass, upload file and return path {valid:true,message:'Upload success!',code:200,url:'files/xxx.jpg'} if (move_uploaded_file($tmp, $path . $image_name)) { //In real scenarios, path needs to be manually concatenated $url = 'ajax/'.$path . $image_name; echoResult(true,'Upload success!',$timestamp,$url,$image_name); exit; } } }
Using new+id
is also possible.
- Output
- HTML
- JS
-
-
-
new orca.Upload('#demo0001',{url:'https://req.orcaui.com/v1/php/upload.php'});
Single File Selection
By default, multiple file selection is enabled, allowing users to select multiple files in the file dialog window through mouse selection or using ctrl/shift shortcuts. If your project only allows uploading one file, set the multiple:false
parameter.
In single selection mode, only one file can be uploaded. To replace the file, the existing one must be deleted first.
- Output
- HTML
File Quantity Limits
The limit
parameter can set file quantity limits, where limit.min
sets the minimum number of files and limit.max
sets the maximum number of files. Both default to 0 (no limit).
- Output
- HTML
Accepted File Types
The accept
parameter sets allowed file types, functioning the same as the native file input's accept
attribute with identical syntax.
- Syntax 1 - Pure extensions: accept=".jpg,.mp4"
- Syntax 2 - Pure MIME types: accept="image/*,video/mp4"
- Syntax 3 - Mixed extensions and MIME: accept=".html,image/*,video/mp4"
Common file type mappings:
Extension | accept Value (MIME) |
---|---|
Any extension | * |
All images | image/* |
All audio | audio/* |
All video | video/* |
.csv | text/csv |
.doc | application/msword |
.docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.ppt | application/vnd.ms-powerpoint |
.pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
.xls | application/vnd.ms-excel |
.xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.wps | application/vnd.ms-works |
.htm | text/html |
.html | text/html |
.jpeg | image/jpeg |
.jpg | image/jpeg |
.png | image/png |
.js | text/javascript, application/javascript |
.css | text/css |
.mp3 | audio/mp3 |
.mp4 | video/mp4 |
.txt | text/plain |
.zip | application/zipapplication/x-zip-compressed |
The difference between this parameter and limit.suffix
is that this parameter restricts visible file types in the selection dialog, while limit.suffix
only performs file type validation before upload.
- Output
- HTML
Thumbnail List
By default, files are displayed in a minimalist list. To show more information like thumbnails and multi-line titles, use the type:'bullet'
parameter.
- Output
- HTML
Grid List
Set type:'cube'
to use a grid list, which is ideal for image uploads.
- Output
- HTML
Card List
Set type:'card'
to use a card list, which displays more text information based on the grid list.
- Output
- HTML
Table
Set type:'table'
to display all file information in tabular form.
- Output
- HTML
Special Structures
The feature
parameter sets fixed-structure upload controls with two current options:
- picture - Fixed cube-type list where selection, upload and delete buttons have same width as images and are aligned at the end
- gallery - Any list type where the list and all buttons are wrapped in an outer frame
Defaults to empty (structure based on type
parameter).
- Output
- HTML
Gallery Structure
The above demonstrates gallery structure with type=text
, but gallery supports all types.
- Output
- HTML
-
type=bullet
type=table
type=cube
type=card
-
Disabled State
Set disabled:true
to disable the instance.
- Output
- HTML
Size
Set size through the size
parameter with options: sm
, md
(default), and lg
. The size only applies to buttons.
- Output
- HTML
Basic Configuration
Property | Type | Default | Description |
---|---|---|---|
name | string | '' | Form hidden field name |
value | string | '' | Initial file value |
url | string | '' | File upload endpoint |
disabled | boolean | false | Whether disabled |
readonly | boolean | false | Whether read-only |
multiple | boolean | true | Whether multi-file selection |
manual | boolean | false | Whether manual upload |
pastable | boolean | true | Whether paste upload allowed |
cols | number | 0 | Number of columns for card type |
Data Source Configuration
Property | Type | Default | Description |
---|---|---|---|
content | string | '' | Data source content |
contType | 'text'/'async'/'html'/'auto'/'' | 'text' | Content type |
contData | object | {} | Request parameters |
ajax | object | {} | Async request config |
Limitation Configuration
Property | Type | Default | Description |
---|---|---|---|
limit.min | number | 0 | Minimum number of files |
limit.max | number | 0 | Maximum number of files |
limit.size | number | 0 | File size limit (MB) |
limit.suffix | string | '' | Allowed file extensions |
accept | string | '' | Allowed MIME types |
Display Configuration
Property | Type | Default | Description |
---|---|---|---|
type | 'text'/'bullet'/'cube'/'card'/'table' | 'text' | List type |
feature | 'picture'/'gallery'/'' | '' | Fixed layout |
size | 'sm'/'md'/'lg' | 'md' | Component size |
table.header | boolean | true | Whether show header |
classes | string | '' | Additional CSS classes |
status | string | '' | Status bar content |
Button Configuration
Property | Type | Default | Description |
---|---|---|---|
chooseBtn.target | string | '' | Select button selector |
chooseBtn.icon | string | '_icon-plus' | Select button icon |
chooseBtn.attrs | object | {} | Select button attributes |
uploadBtn.enable | boolean | false | Whether enable upload button |
uploadBtn.target | string | '' | Upload button selector |
uploadBtn.icon | string | '_icon-upload' | Upload button icon |
uploadBtn.attrs | object | {} | Upload button attributes |
clearBtn.enable | boolean | false | Whether enable clear button |
clearBtn.target | string | '' | Clear button selector |
clearBtn.icon | string | '_icon-trash' | Clear button icon |
clearBtn.attrs | object | {} | Clear button attributes |
Cloud Storage Configuration
Property | Type | Default | Description |
---|---|---|---|
cloud.enable | boolean | false | Whether enable cloud |
cloud.field | string | '' | Field name |
cloud.server | string | '' | Server address |
cloud.domain | string | '' | Domain address |
cloud.map.name | string | '' | Name field mapping |
cloud.map.url | string | '' | URL field mapping |
cloud.map.size | string | '' | Size field mapping |
cloud.map.time | string | '' | Time field mapping |
Before Functions
Property | Type | Default | Description |
---|---|---|---|
b4Clear | function | null | Before clear callback |
b4Remove | function | null | Before remove callback |
b4Upload | function | null | Before upload callback |
b4UploadAll | function | null | Before batch upload |
Callback Functions
Property | Type | Default | Description |
---|---|---|---|
onRendered | function | null | After render callback |
onAdded | function | null | After add callback |
onRemoved | function | null | After remove callback |
onCleared | function | null | After clear callback |
onPasted | function | null | Paste upload callback |
onDropped | function | null | Drop upload callback |
onUploading | function | null | Uploading callback |
onUploaded | function | null | Upload complete callback |
onReceived | function | null | Server receive callback |
onReceivedAll | function | null | Batch receive callback |
onUploadAll | function | null | Start batch upload callback |
onUploadedAll | function | null | Batch upload complete |
onFailed | function | null | Upload failed callback |
onError | function | null | Error callback |
onOutput | function | null | Output value callback |
onUpdatedCont | function | null | Content update callback |
onRequest | function | null | Request complete callback |
onPassivated | function | null | Disable callback |
onActivated | function | null | Enable callback |