jQuery Ajax 文件异步上传,选择文件后直接上传图片 无上传按钮的一个上传
XML/HTML Code
- <div class="row">
- <div class="col-md-6 col-sm-12">
- <!-- Our markup, the important part here! -->
- <div id="drag-and-drop-zone" class="dm-uploader p-5">
- <h3 class="mb-5 mt-5 text-muted">Drag & drop files here</h3>
- <div class="btn btn-primary btn-block mb-5">
- <span>Open the file Browser</span>
- <input type="file" title='Click to add Files' />
- </div>
- </div><!-- /uploader -->
- </div>
- <div class="col-md-6 col-sm-12">
- <div class="card h-100">
- <div class="card-header">
- File List
- </div>
- <ul class="list-unstyled p-2 d-flex flex-column col" id="files">
- <li class="text-muted text-center empty">No files uploaded.</li>
- </ul>
- </div>
- </div>
- </div><!-- /file list -->
- <div class="row">
- <div class="col-12">
- <div class="card h-100">
- <div class="card-header">
- Debug Messages
- </div>
- <ul class="list-group list-group-flush" id="debug">
- <li class="list-group-item text-muted empty">Loading plugin....</li>
- </ul>
- </div>
- </div>
- </div> <!-- /debug -->
PHP Code
- <?php
- /*
- This is a ***DEMO*** , the backend / PHP provided is very basic. You can use it as a starting point maybe, but ***do not use this on production***. It doesn't preform any server-side validation, checks, authentication, etc.
- For more read the README.md file on this folder.
- Based on the examples provided on:
- - http://php.net/manual/en/features.file-upload.php
- */
- header('Content-type:application/json;charset=utf-8');
- try {
- if (
- !isset($_FILES['file']['error']) ||
- is_array($_FILES['file']['error'])
- ) {
- throw new RuntimeException('Invalid parameters.');
- }
- switch ($_FILES['file']['error']) {
- case UPLOAD_ERR_OK:
- break;
- case UPLOAD_ERR_NO_FILE:
- throw new RuntimeException('No file sent.');
- case UPLOAD_ERR_INI_SIZE:
- case UPLOAD_ERR_FORM_SIZE:
- throw new RuntimeException('Exceeded filesize limit.');
- default:
- throw new RuntimeException('Unknown errors.');
- }
- $filepath = sprintf('../../uploadpic/%s_%s', uniqid(), $_FILES['file']['name']);
- if (!move_uploaded_file(
- $_FILES['file']['tmp_name'],
- $filepath
- )) {
- throw new RuntimeException('Failed to move uploaded file.');
- }
- // All good, send the response
- echo json_encode([
- 'status' => 'ok',
- 'path' => $filepath
- ]);
- } catch (RuntimeException $e) {
- // Something went wrong, send the err message as JSON
- http_response_code(400);
- echo json_encode([
- 'status' => 'error',
- 'message' => $e->getMessage()
- ]);
- }
原文地址:http://www.freejs.net/article_biaodan_759.html