建议使用jquery修复以下代码

时间:2016-07-25 16:21:39

标签: javascript jquery json ajax django

当您选择文件

<input id="chunked_upload" type="file" name="the_file">

以下代码处理不同部分的文件上传自动运行

            var md5 = "",
            csrf = $("input[name='csrfmiddlewaretoken']")[0].value,
            form_data = [{"name": "csrfmiddlewaretoken", "value": csrf}];
        function calculate_md5(file, chunk_size) {
          var slice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
              chunks = chunks = Math.ceil(file.size / chunk_size),
              current_chunk = 0,
              spark = new SparkMD5.ArrayBuffer();
          function onload(e) {
            spark.append(e.target.result);  // append chunk
            current_chunk++;
            if (current_chunk < chunks) {
              read_next_chunk();
            } else {
              md5 = spark.end();
            }
          };
          function read_next_chunk() {
            var reader = new FileReader();
            reader.onload = onload;
            var start = current_chunk * chunk_size,
                end = Math.min(start + chunk_size, file.size);
            reader.readAsArrayBuffer(slice.call(file, start, end));
          };
          read_next_chunk();
        }
        $("#chunked_upload").fileupload({
          url: "{% url 'api_chunked_upload' %}",
          dataType: "json",
          maxChunkSize: 100000, // Chunks of 100 kB
          formData: form_data,
          add: function(e, data) { // Called before starting upload
            $("#messages").empty();
            // If this is the second file you're uploading we need to remove the
            // old upload_id and just keep the csrftoken (which is always first).
            form_data.splice(1);
            calculate_md5(data.files[0], 100000);  // Again, chunks of 100 kB
            data.submit();
          },
          chunkdone: function (e, data) { // Called after uploading each chunk
            if (form_data.length < 2) {
              form_data.push(
                {"name": "upload_id", "value": data.result.upload_id}
              );
            }
            $("#messages").append($('<p>').text(JSON.stringify(data.result)));
            var progress = parseInt(data.loaded / data.total * 100.0, 10);
            /*$("#progress").text(Array(progress).join("=") + "> " + progress + "%");*/
            $('#progress .progress-bar').css('width',progress + '%');
            $('#progress .progress-bar').css('aria-valuenow',progress + '%');
          },
          done: function (e, data) { // Called when the file has completely uploaded
            $.ajax({
              type: "POST",
              url: "{% url 'api_chunked_upload_complete' %}",
              data: {
                csrfmiddlewaretoken: csrf,
                upload_id: data.result.upload_id,
                md5: md5
              },
              dataType: "json",
              success: function(data) {
                $("#messages").append($('<p>').text(JSON.stringify(data)));

              }
            });
          },
        });

但我不希望代码自动执行。直到你只需点击下一个按钮

<button id="enviar">Saludar</button>
有人建议我怎么做

1 个答案:

答案 0 :(得分:0)

  • button#enviar添加点击监听器。

然后

  • 移动fileupload来电 内部此次点击事件的回调:

     $('button#enviar').click(function(){
    
              $("#chunked_upload").fileupload(
    
                  //....
    
    
       })
    

整个代码变为:

           var md5 = "",
            csrf = $("input[name='csrfmiddlewaretoken']")[0].value,
            form_data = [{"name": "csrfmiddlewaretoken", "value": csrf}];
        function calculate_md5(file, chunk_size) {
          var slice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
              chunks = chunks = Math.ceil(file.size / chunk_size),
              current_chunk = 0,
              spark = new SparkMD5.ArrayBuffer();
          function onload(e) {
            spark.append(e.target.result);  // append chunk
            current_chunk++;
            if (current_chunk < chunks) {
              read_next_chunk();
            } else {
              md5 = spark.end();
            }
          };
          function read_next_chunk() {
            var reader = new FileReader();
            reader.onload = onload;
            var start = current_chunk * chunk_size,
                end = Math.min(start + chunk_size, file.size);
            reader.readAsArrayBuffer(slice.call(file, start, end));
          };
          read_next_chunk();
        }
        $('#enviar').click(function(){

                 uploadFile();
          });

然后uploadFile是:

function uploadFile(){
       $("#chunked_upload").fileupload({
              url: "{% url 'api_chunked_upload' %}",
              dataType: "json",
              maxChunkSize: 100000, // Chunks of 100 kB
              formData: form_data,
              add: function(e, data) { // Called before starting upload
                $("#messages").empty();
                // If this is the second file you're uploading we need to remove the
                // old upload_id and just keep the csrftoken (which is always first).
                form_data.splice(1);
                calculate_md5(data.files[0], 100000);  // Again, chunks of 100 kB
                data.submit();
              },
              chunkdone: function (e, data) { // Called after uploading each chunk
                if (form_data.length < 2) {
                  form_data.push(
                    {"name": "upload_id", "value": data.result.upload_id}
                  );
                }
                $("#messages").append($('<p>').text(JSON.stringify(data.result)));
                var progress = parseInt(data.loaded / data.total * 100.0, 10);
                /*$("#progress").text(Array(progress).join("=") + "> " + progress + "%");*/
                $('#progress .progress-bar').css('width',progress + '%');
                $('#progress .progress-bar').css('aria-valuenow',progress + '%');
              },
              done: function (e, data) { // Called when the file has completely uploaded
                $.ajax({
                  type: "POST",
                  url: "{% url 'api_chunked_upload_complete' %}",
                  data: {
                    csrfmiddlewaretoken: csrf,
                    upload_id: data.result.upload_id,
                    md5: md5
                  },
                  dataType: "json",
                  success: function(data) {
                    $("#messages").append($('<p>').text(JSON.stringify(data)));

                  }
                });
              },
            });


}