支持AJAX 实时预览文件上传程序 jQuery上传程序.js

  • 源码大小:18.23KB
  • 所需积分:1积分
  • 源码编号:19JP-3509
  • 浏览次数:278次
  • 最后更新:2023年06月21日
  • 所属栏目:表单
本站默认解压密码:19jp.com 或 19jp_com

简介

一个轻量级且支持AJAX的文件上传器插件,为通过AJAX上传单个或多个文件提供了方便的解决方案。

它允许用户从本地选择文件,在浏览器中预览文件,并在选择后自动上传这些文件。

参见:

  • jQuery和Vanilla JavaScript中的10个最佳文件上传库

如何使用它:

1.在文档中加载jQuery Uploader插件的文件。

<!-- Font Awesome Iconic Font Is Required -->
<link rel="stylesheet" href="/path/to/cdn/font-awesome.min.css">

<!-- jQuery Is Required -->
<script src="/path/to/cdn/jquery.min.js"></script>

<!-- jQuery Uploader Files -->
<link rel="stylesheet" href="./css/jquery.uploader.css">
<script src="./dist/jquery.uploader.min.js"></script>

2.为文件上传器创建一个输入字段。

<input type="text" id="example" value="" />

3.初始化插件以创建一个基本的文件上传器。

$("#example").uploader({
  // options
})

4.启用多文件上传。

$("#example").uploader({
  multiple: true,
})

5.设置上传模式:“url”、“file”或“custom”。

$("#example").uploader({
  mode: Uploader.mode.file,
})

6.启用自动上传。默认值:true。

$("#example").uploader({
  autoUpload: false,
})

7.定义预先选择的文件。

$("#example").uploader({
  defaultValue: [
    {
      name: "jquery",
      url: "/path/to/jquery.jpg"
    }, {
      name: "script",
      url: "/path/to/script.png"
    }
  ],
})

8.配置ajax上传。

$("#example").uploader({
  ajaxConfig: {
    url: "",
    method: "post",
    paramsBuilder: function (uploaderFile) {
      let form = new FormData();
      form.append("file", uploaderFile.file)
      return form
    },
    ajaxRequester: function (config, uploaderFile, progressCallback, successCallback, errorCallback) {
      $.ajax({
        url: config.url,
        contentType: false,
        processData: false,
        method: config.method,
        data: config.paramsBuilder(uploaderFile),
        success: function (response) {
          successCallback(response)
        },
        error: function (response) {
          console.error("Error", response)
          errorCallback("Error")
        },
        xhr: function () {
          let xhr = new XMLHttpRequest();
          xhr.upload.addEventListener('progress', function (e) {
              let progressRate = (e.loaded / e.total) * 100;
              progressCallback(progressRate)
          })
          return xhr;
        }
      })
    },
    responseConverter: function (uploaderFile, response) {
      return {
        url: response.data,
        name: null,
      }
    },
  },
})

9.事件处理程序。

$("#example").uploader()
.on("uploader-init", function() {
  // do something
},
.on("before-upload", function(waitUploadFiles) {
  // do something
},
.on("uploading", function(file) {
  // do something
},
.on("upload-success", function(file, data) {
  // do something
},
.on("upload-error", function() {
  // do something
},
.on("file-add", function() {
  // do something
},
.on("file-remove", function() {
  // do something
},

10.API方法。

// upload files manually
upload();

// clear all files
clean();

// get all files
uploadFiles();

预览截图