【问题标题】:passing custom variables to formstone将自定义变量传递给 Formstone
【发布时间】:2019-11-07 23:05:02
【问题描述】:

我在我的 ajax 驱动表单中使用 formstone 拖放文件上传。使用 $(".uploadImage").upload("start") 和 $(".uploadDocs").upload("start") 在 ajax 函数响应后分别初始化图像和文档的上传部分。每个函数都可以工作,但我想将一个自定义变量(例如文件夹名称)传递给 formstone 并创建一个具有该名称的文件夹并将图像和文档上传到该文件夹​​。该怎么做?

插入发生并返回 id 的 Ajax 函数


$.ajax({
 type: 'POST',
 url: base_url + 'innovation/addProcess',
 dataType: "html",
 data: $('#add_innovation').serialize(),
 success: function(result) {

    var res = result.split("#");
    if (res[0] == 'success') {
       $(".uploadImage").upload("start",postData: {"ideaId":10});// sending custom value to formstone, which is not working as of now
       $(".uploadDocs").upload("start",postData: {"ideaId":10});
     } else {   
        showNotification('alert-danger', result);
     }

    },
     error: function(error) {
        console.log('error');
     }
 });

Formstone 初始化


Formstone.Ready(function() {

  $(".uploadImage").upload({            
    maxSize: 1073741824,
    beforeSend: onBeforeSend,
    autoUpload: false,
    //postData: {"ideaId":50} // this is working. but don't want this here
  }).on("start.upload", onStart)
  .on("complete.upload", onComplete)
  .on("filestart.upload", onFileStart)
  .on("fileprogress.upload", onFileProgress)
  .on("filecomplete.upload", onFileComplete)
  .on("fileerror.upload", onFileError)
  .on("queued.upload", onQueued);

$(".uploadDocs").upload({            
  maxSize: 1073741824,
  beforeSend: onBeforeSend,
  autoUpload: false,
}).on("start.upload", onStart)
.on("complete.upload", onComplete)
.on("filestart.upload", onFileStart)
.on("fileprogress.upload", onFileProgress)
.on("filecomplete.upload", onFileComplete)
.on("fileerror.upload", onFileError)
.on("queued.upload", onQueued);

});

function onCancel(e) {
   console.log("Cancel");
   var index = $(this).parents("li").data("index");
   $(this).parents("form").find(".upload").upload("abort", 
   parseInt(index, 10));
}

function onCancelAll(e) {
  console.log("Cancel All");
  $(this).parents("form").find(".upload").upload("abort");
}

function onBeforeSend(formData, file) {     

 console.log(formData.get("ideaId")); // here i need the posted data. currently its not getting here

 formData.append("ideaId", ideaId);
 return ((file.name.indexOf(".jpg") <= -1) && (file.name.indexOf(".png") <= -1)) ? false : formData; // cancel all jpgs

 }

function onQueued(e, files) {
    console.log("Queued");
    var html = '';
    for (var i = 0; i < files.length; i++) {
      html += '<li data-index="' + files[i].index + '"><span class="content"><span class="file">' + files[i].name + '</span><span class="cancel">Cancel</span><span class="progress">Queued</span></span><span class="bar"></span></li>';
   }

  $(this).parents("form").find(".filelist.queue")
    .append(html);
 }

 function onStart(e, files) {

   $(this).parents("form").find(".filelist.queue")
    .find("li")
    .find(".progress").text("Waiting");
 }

 function onComplete(e) {
  console.log("Complete");
  // All done!
 }

function onFileStart(e, file) {
  console.log("File Start");
  $(this).parents("form").find(".filelist.queue")
    .find("li[data-index=" + file.index + "]")
    .find(".progress").text("0%");
 }

function onFileProgress(e, file, percent) {
  console.log("File Progress");
   var $file = $(this).parents("form").find(".filelist.queue").find("li[data-index=" + file.index + "]");

  $file.find(".progress").text(percent + "%")
  $file.find(".bar").css("width", percent + "%");
}

function onFileComplete(e, file, response) {
  console.log("File Complete");
  if (response.trim() === "" || response.toLowerCase().indexOf("error") > -1) {
     $(this).parents("form").find(".filelist.queue")
        .find("li[data-index=" + file.index + "]").addClass("error")
        .find(".progress").text(response.trim());
  } else {
    var $target = 
     $(this).parents("form").find(".filelist.queue").find("li[data-index=" + file.index + "]");
      $target.find(".file").text(file.name);
      $target.find(".progress").remove();
      $target.find(".cancel").remove();




$target.appendTo($(this).parents("form").find(".filelist.complete"));
    }
  }

   function onFileError(e, file, error) {
     console.log("File Error");
     $(this).parents("form").find(".filelist.queue")
    .find("li[data-index=" + file.index + "]").addClass("error")
    .find(".progress").text("Error: " + error);
  }

我使用 formstone 控件的 HTML


<div class="uploadImage" style="height:100px;border:1px dashed #000;" data-upload-options='{"action":"<?php echo base_url();?>innovation/uploadImage","chunked":true}'></div>


<div class="uploadDocs" style="height:100px;border:1px dashed #000;" data-upload-options='{"action":"<?php echo base_url();?>innovation/uploadDocs","chunked":true}'></div>

【问题讨论】:

  • 您可以使用选项参数postData 传递额外的数据,例如文件夹名称。只需参考Documentation
  • @CodyKL 你的意思是像 $(".uploadImage").upload("start",postDate:{'userId':10}) ?
  • @CodyKL 文件夹名称类似于数字,每个 ajax 响应都会有所不同。该过程是当用户按下提交按钮时,它使用 ajax 插入一些数据,并给出一个数字作为响应。 ajax响应成功后需要创建一个文件夹(文件夹的名称是从响应中获取的编号)并将图片或文档上传到文件夹。
  • 关于您的第一条评论:是的,正是通过这种方式您传递了额外的数据。然后在服务器端创建文件夹(通过 PHP 或其他方式,我不知道您在服务器端使用哪种语言来处理表单数据)。
  • @CodyKL 发布时 $(".uploadImage").upload("start",postData: {"ideaId":10});像这样不起作用,我无法获取 formData 变量中的数据。但通过 $(".uploadImage").upload({ maxSize: 1073741824, beforeSend: onBeforeSend, autoUpload: false, postData: {"ideaId":50} });在初始化时是有效的。我刚刚在这里硬编码了idea id,实际上它应该来自formstone调用的部分。

标签: php jquery file-upload


【解决方案1】:

试试这个...

.ajax({
 type: 'POST',
 url: base_url + 'innovation/addProcess',
 dataType: "html",
 data: $('#add_innovation').serialize(),
 success: function(result) {

    var res = result.split("#");
    if (res[0] == 'success') {
       $(".uploadImage").upload("defaults", {postData: {"ideaId":10}});
       $(".uploadImage").upload("start");
       $(".uploadDocs").upload("defaults", {postData: {"ideaId":10}});
       $(".uploadDocs").upload("start");
     } else {   
        showNotification('alert-danger', result);
     }

    },
     error: function(error) {
        console.log('error');
     }
 });

在调用方法“start”之前,您需要添加选项“postData”。据我从文档中了解到,“开始”方法不允许额外的参数。

【讨论】:

  • 如果您在 ajax 调用的响应中得到 ideaId,那么只需像这样添加它:{postData: {"ideaId":res[x]}}(将 x 替换为包含 ID 的元素的编号)。跨度>
  • 已经尝试过您提到的代码,不幸的是,它不起作用。 formData.get("ideaId") 这就是我尝试访问发布的数据的方式,但没有得到任何东西。如果我通过 formstone 初始化发布数据,同样会得到数据。
  • 抱歉,我在您的代码中没有看到方法 formData.get() 或变量 formData
  • 我更新了 Formstone 初始化部分,数据正在访问。
【解决方案2】:

CodyKL 的解决方案使用defaults 方法工作,或者您可以使用beforeSend 回调附加额外的参数:

// Var to store ID of inserted item
var resultId;

// Insertion AJAX
$.ajax({
  ...
  success: function(result) {
    // Get the id from the result
    resultId = result;

    // Start the upload
    $(".uploadImage").upload("start");
  },
  ...
});

// Initialize Upload
$(".uploadImage").upload({
  ...
  beforeSend: onBeforeSend,
  ...
});

// Modify upload form data 
function onBeforeSend(formData, file) {
  formData.append('ideaId', resultId); // add resultID obtained in insertion AJAX above to form data

  return formData; // Return modified formData
}

您应该阅读 JS 和 FormData API 的工作原理:https://developer.mozilla.org/en-US/docs/Web/API/FormData

【讨论】:

    猜你喜欢
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    相关资源
    最近更新 更多