JQuery 上传文件并显示上传进度

贺子昂
2023-12-01

上传文件&显示上传进度

  • 本文使用 jQuery 异步上传文件,并使用 PHP (Magento1 & Laravel) 进行后端处理。
  • 需配置文件上传参数,如 upload_max_filesizepost_max_size 等。参考文章:配置PHP上传文件大小限制

1. html:

<style type="text/css">
	form.upload-file>div { margin: 40px; }
	form.upload-file label { font-size: 16px; font-weight: normal; width: 120px; }
	form.upload-file input[type=text], form.upload-file select { width: 365px; height: 40px; }
	form.upload-file .btn { display: inline-block; position: relative; padding: 10px 40px; background-color: #666; color: #fff; cursor: pointer; }
	form.upload-file .btn span { overflow: hidden; position: absolute; top: 0; left: 0px; width: 151px; height: 37px; }
	form.upload-file .btn input { position: absolute; top: 0; left: -72px; width: 224px; height: 37px; cursor: pointer; opacity: 0; }
	form.upload-file .filename, form.upload-file .message { margin-left: 40px; font-weight: 700; }
	form.upload-file .upload-status { display: none; position: relative; margin-left: 40px; width: 365px; text-align: center; z-index: 1; }
	form.upload-file .upload-status.active { display: inline-block; }
	form.upload-file .upload-status>div { position: absolute; top: 0; height: 30px; width: 0%; background-color: #90cc84; border-radius: 5px; z-index: -1; }
	form.upload-file .upload-status>p { height: 30px; line-height: 30px; border: 1px solid #ccc; border-radius: 5px; margin-bottom: 0; }
	form.upload-file .btn.submit{ background: #3399cc; width: 150px; text-align: center; }
	form.upload-file .btn.submit:hover { background: #2e8ab8; }
</style>

<h1>Upload Files</h1>

<form class="upload-file" enctype="multipart/form-data">
	<div>
		<label for="upload_code" class="required">Upload Code</label>
		<input type="text" name="upload_code" id="upload_code" />
	</div>

	<div>
		<label for="upload_type" class="required">Upload Type</label>
		<select name="upload_type" id="upload_type">
			<option value="">Please select upload type</option>
			<option value="Price List">Price List</option>
			<option value="Product Catalog">Product Catalog</option>
			<option value="Product Warranty Policy">Product Warranty Policy</option>
			<option value="Shipment Policy">Shipment Policy</option>
			<option value="Payment Option">Payment Option</option>
		</select>
	</div>

    <div class="add-file">
        <label  class="required">Browser File</label>
    	<span class="btn">
    		Upload File
        	<span><input type="file" name="file" id="file" accept=".pdf, .csv, .xls, .xlsx"></span>
		</span>
		<span class="filename"></span>
    </div>

    <div>
		<label>&nbsp;</label>
		<span class="btn submit">Submit</span>
		<span class="message"></span>

	    <div class="upload-status">
	      <div class="uploaded"></div>
	      <p class="upload-progress"><span>0</span>%</p>
	    </div>
	</div>
</form>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

2. jQuery 异步上传

	$('body').on('change', '.upload-file input[type="file"]', function(){
	  var _file = $(this).val()
	  var _text = ''
	  if (_file != ''){
	    _file = _file.split('\\')
	    _text = _file[_file.length - 1]
	  }
	  $('.upload-file .add-file .filename').text(_text)
	  $('.upload-file .message').text('')
	})
	$('body').on('change', '.upload-file select', function(){
	  $('.upload-file .message').text('')
	})
	
	// 开始上传
	$('body').on('click', '.upload-file .btn.submit', function(){
	  $('.upload-file .message').text('')
	
	  var _upload_code = $('#upload_code').val()
	  var _upload_type = $('#upload_type').val()
	  var _file = $('#file').val()
	
	  if (_upload_code == '' || _upload_type == '' || _file == '') {
	    alert('Please Entry Info')
	    return
	  }
	
	  var _form = $(this).closest('form')
	  var formData = new FormData(_form[0])
	  // console.log(formData)
	
	  $.ajax({
	    type: 'POST',
	    url: '/api/uploadFiles.php',
	    data: formData,
	    xhr: function() {
	      var myXhr = $.ajaxSettings.xhr()
	      if(myXhr.upload){
	        $('.upload-file .upload-status').addClass('active')
	        myXhr.upload.addEventListener(
	          'progress', 
	          progress,   // 用于显示上传进度
	          false)
	      }
	      return myXhr
	    },
	    cache:false,
	    contentType: false,
	    processData: false,
	  }).done(function(response){
	      $('.upload-file .message').text($.parseJSON(response).message)
	  })
	})
	
	// 用于显示上传进度
	function progress(e){
	  if(e.lengthComputable){
	    var max = e.total
	    var current = e.loaded
	    var Percentage = (current * 100)/max
	    // console.log(Percentage)
	    $('.upload-status .uploaded').css('width', Percentage + '%')
	    $('.upload-status .upload-progress span').text(Percentage.toFixed(2))
	    if (Percentage >= 100) {
	      $('.upload-file .upload-status').removeClass('active')
	      $('.upload-status .uploaded').css('width', 0)
	      $('.upload-status .upload-progress span').text(0)
	    }
	  }
	}

3. 后端处理

  • Magento

      // $_params = file_get_contents("php://input");
      // $_params = json_decode($_params, true);
      // if(!isset($_params['token']) || $_params['token'] != '8jhdy29kdj67hd'){
      //   return false;
      // }
    
      error_reporting(E_ALL | E_STRICT);
      define('MAGENTO_ROOT', '../');
    
      $_mage_file = MAGENTO_ROOT . '/app/Mage.php';
      require_once $_mage_file;
      umask(0);
      Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    
      require_once('config.php');
      $result = false;
      if (isset($_FILES['file']) && file_exists($_FILES['file']['tmp_name'])) {
          $uploader = new Varien_File_Uploader('file');
          $uploader->setAllowedExtensions(array('pdf', 'csv', 'xls', 'xlsx'));
          $uploader->setAllowRenameFiles(false);
          $path1 = Mage::getBaseDir('media') . DS . 'files' . DS;
          $path2 = '/media/files/';
          $name = $_FILES['file']['name'];
          $result = $uploader->save($path1, $name);
    
          if ($result) {
          	$name = $_POST['upload_type'];
          	$date = date('Y.m.d');
          	$file = $result['file'];
          	$path = $path2.$result['file'];
          	$size = ceil($result['size'] / 1024);
          	if ($size < 1024) {
          		$unit = ' KB';
          	} else {
          		$size = ceil($size / 1024);
          		$unit = ' MB';
          	}
    
      		$resource = Mage::getSingleton("core/resource");
      		$write = $resource->getConnection('core_write');
      		$table = $resource->getTableName('smallrig_files');
    
      		// $result2 = $write->insert($table, ['name' => $name, 'date' => $date, 'size' => $size.$unit, 'path' => $path]);
       		$result2 = $write->update($table, ['date' => $date, 'file' => $file, 'size' => $size.$unit, 'path' => $path], ['name=?' => $name]);
      		   
          	if ($result2) {
          		echo json_encode(['success' => true, 'message' => 'Upload Success']);
          	} else {
          		echo json_encode(['success' => false, 'message' => 'Upload failure']);
          	}
      	    
      	} else {
      	    echo json_encode(['success' => false, 'message' => 'Upload failure']);
      	}
      } else {
          echo json_encode(['success' => false, 'message' => 'Please add file']);
      }
    
  • Laravel

      if ($request->hasFile('document') && $request->file('document')->isValid()) {
        $filesize = round(($request->file('document')->getClientSize() / 1024), 2);
        if ($filesize > 20480) {
          return response()->json([
              'success' => false,
              'message' => 'The file size should be within 20M',
              'data' => ''
            ]);
        }
        if (!Cache::has(session('cid').'_project_quote_id')) {
          $_project_model = new Project;
          $_create = [
            'increment_id' => '',
            'client_id' => session('cid'),
            'name' => '',
            'product_name' => '',
            'status_id' => 0,
            'order_quantity' => 0,
            'supplier_name' => '',
            'supplier_contact_name' => '',
            'supplier_contact_telephone' => '',
            'supplier_contact_email' => '',
            'supplier_address' => '',
            'supplier_city' => '',
            'supplier_region' => '',
            'supplier_country' => '',
            // 'expected_order_ready_date' => '',
          ];
          $_result = $_project_model->create($_create);
          Cache::forever(session('cid').'_project_quote_id', $_result['id']);
        }
        $project_id = Cache::get(session('cid').'_project_quote_id');
    
        $filesize = $filesize.'KB';
        $date = date('d/m/Y');
        $file = $request->file('document');
        $originName = $file->getClientOriginalName();
        $entension = $file->getClientOriginalExtension();
        $_fresult = $file->move('documents/'.session('cid').'/'.date('Y-m-d').'/project', md5(uniqid($file->getfileName(), true)).'.'.$entension);
        $documents = '/'.$_fresult->getpathName();
    
        $fileType = $entension;
        if (in_array($entension, ['doc', 'docx', 'docm', 'dotx', 'dotm']))
          $fileType = 'word';
        if (in_array($entension, ['xls', 'xlsx']))
          $fileType = 'excel';
    
        $_project_file_model = new ProjectFile;
        $_files = [
          'project_id' => $project_id,
          'filename' => $originName,
          'file_type' => $fileType,
          'date' => $date,
          'size' => $filesize,
          'path' => $documents,
        ];
        $_upload_result = $_project_file_model->create($_files);
        $project_file_id = $_upload_result['id'];
    
        return response()->json([
            'success' => true,
            'message' => 'Upload Success',
            'data' => ['project_file_id' => $project_file_id, 'fileType' => $fileType, 'documents' => $documents, 'originName' => $originName, 'date' => $date, 'filesize' => $filesize]
          ]);
      }
    






 类似资料: