【问题标题】:How to Preview Files First and Click Button to Upload and Save Multiple Files如何先预览文件并单击按钮上传和保存多个文件
【发布时间】:2014-09-29 22:26:39
【问题描述】:

我正在测试下面的这段代码,我在上传多个图像之前预览图像文件,但是我在获取脚本来保存和上传文件时遇到了一些问题。大部分代码来自这个网站:https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

花了整整两个小时在这个上传脚本上蹦蹦跳跳,我无法让 JavaScript 函数 FileUpload() 工作。 我不是这方面的专家,所以我很想问是否有人可以给我一个线索,说明什么可能导致代码无法上传文件。 指针: 我正在使用 IE11 和 Firefox v32。 该网站还提供了一个注释,见下文;但我不确定如何进行更改以将文件作为 blob 发送: 注意:上例中的非标准 sendAsBinary 方法自 Gecko 31 (Firefox 31 / Thunderbird 31 / SeaMonkey 2.28) 起已被弃用,并将很快被删除。可以使用标准的 send(Blob data) 方法。

HTML/JavaScript

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>test file upload</title>
<link rel="stylesheet" href="style.css" type="text/css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" charset="utf-8"></script>

</head>

<body>

    <h2><strong>Multiple Images Upload</strong></h2>
    <p>Upload only files with: .jpeg, .jpg, .gif &amp; .png. extensions.</p>
    <br>
    <div class="row"><!-- Start button-progress row --> 
        <form name="upl-form" method="post" enctype="multipart/form-data" >
            <input type="file" id="myfile" name="myfile" accept="image/*" multiple  onchange="showFiles(this.files)"/>
            <button id="upl"> <strong>upload</strong></button>
            <button id="rem"> <strong>Remove</strong></button>
        </form>
    </div>
    <div class="clear-both"></div> 
    <div id="row">
        <p id="upl_msg"></p><!-- messages -->
        <div class="progress"></div><!-- progress -->
    </div>
    <div class="clear-both"></div> 
    <div class="row">
        <ul id="preview">
            <!-- preview the selected files here --> 
        </ul>
    </div>

<script>

    // set form upload/reset buttons handle events
    var form = document.forms.namedItem("upl-form");

    // reset - button
    form.addEventListener('rem', function(ev) {
    this.form.reset();
      ev.preventDefault();
    }, false);

    // upload - button
    var upl = document.getElementById("upl"),
        obj = {
            handleEvent: function() {
                sendFiles();
            }
        };

    upl.addEventListener("click", obj, function(e) {
        e.preventDefault();
    }, false);


    // preview image files
    function showFiles(files) 
    {
        // get the preview area ID
        preview = document.getElementById("preview");
        preview.setAttribute("class", "small-block");

        // loop through the selected files source
        for (var i = 0; i < files.length; i++)
        {
            // seperate the files and check the allowed file types
            var file = files[i];
            var imageType = /image.*/;

            if (!file.type.match(imageType)) 
            {
              continue;
            }

            // for previewing, create the image elememt
            var img = document.createElement("img");
            img.setAttribute("class", "th qd-thumb");
            img.classList.add("obj");
            img.file = file;
            preview.appendChild(img); 

            // start the file reader
            var reader = new FileReader();
            reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
            reader.readAsDataURL(file);                                     
        }
    }

    function sendFiles() {
      var imgs = document.querySelectorAll(".obj");

      for (var i = 0; i < imgs.length; i++) {
        new FileUpload(imgs[i], imgs[i].file);
      }
    }

    function FileUpload(img, file) {
      var reader = new FileReader();  
      this.ctrl = createThrobber(img);
      var xhr = new XMLHttpRequest();
      this.xhr = xhr;

      var self = this;
      this.xhr.upload.addEventListener("progress", function(e) {
            if (e.lengthComputable) {
              var percentage = Math.round((e.loaded * 100) / e.total);
              self.ctrl.update(percentage);
            }
          }, false);

      xhr.upload.addEventListener("load", function(e){
              self.ctrl.update(100);
              var canvas = self.ctrl.ctx.canvas;
              canvas.parentNode.removeChild(canvas);
          }, false);
      xhr.open("POST", "http://localhost/test.com/upload.php");
      xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
      reader.onload = function(evt) {
        xhr.sendAsBinary(evt.target.result);
      };
      reader.readAsBinaryString(file);
    }

</script>

</body>
</html>

<?php
if (isset($_FILES['myFile'])) {
    // Example:
    move_uploaded_file($_FILES['myfile']['tmp_name'], "uploads/" . $_FILES['myfile']['name']);
    exit;
}

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    一个不错的 jQuery 文件上传插件可用

    为什么要从头开始写?有一个很好的基于 jQuery HTML5 的插件可用。

    http://blueimp.github.io/jQuery-File-Upload/

    它还为非 HTML5 浏览器和禁用 JS 的浏览器提供后备选项。它适用于许多服务器端平台,如 PHP、Python、Ruby on Rails、Java、Node.js 等......

    您还可以在

    找到相同的 WordPress 插件实现

    https://wordpress.org/plugins/jquery-html5-file-upload/

    猜你喜欢
    • 2012-06-04
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    相关资源
    最近更新 更多