【问题标题】:multiple images upload using FormData and separate fields使用 FormData 和单独的字段上传多个图像
【发布时间】:2018-02-20 09:21:24
【问题描述】:

我想在提交表单之前开始上传图片到服务器 不能嵌套表单,所以我使用 formdata()

表格包含标题和5张带标题的图片,一旦我选择图片而不点击上传,我想开始上传,并且不提交主表格,防止在上传图片之前提交表格

这是代码的一部分 它仅适用于第一个输入

    $(document).ready(function(){

    var counter = 2;



    $("#howaddButton").click(function () {

    if(counter>25){
    alert("error");
    return false;
    }



    $('#file' counter +).change(function(){
    var file_data = $('#file' counter +).prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file' counter +, file_data);
    $.ajax({
        url: "upload.php",
        type: "POST",
        data:  form_data,
        contentType: true,
        cache: false,
        processData:true,



        success: function(data){
            console.log(data);

        }

    });
    });



    var newTextBoxDiv = $(document.createElement('div'))
    .attr("id", 'howTextBoxDiv' + counter);

    newTextBoxDiv.after().html(

    '<span id="content' + counter + '"><div class="btn btn-primary btn-file alert">'+

        '<div id="response">'+'</div>'+

    '<input type="file'+ counter +'" name="file'+ counter +'" id="file'+ counter +'">'+



    '</div></span>');

});

});

..

<div id="howTextBoxesGroup">
<div id="howTextBoxDiv1">

<li><a>
<input class="form-control input-md" placeholder="" required="required" type="textbox" name="how[0]" >
</a></li>



<span id="content">
    <div class="btn btn-primary btn-file alert"> 

    <div id="response"></div>

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


</div>
</span>


</div>
</div>

<button class="btn btn-success"   name="plus" id="howaddButton" type="button">+</button>
<button  class="btn btn-primary" name="minus" id="howremoveButton" type="button">-</button>

我认为这是问题所在

        '<div id="response">'+'</div>'+

        '<input type="file" name="file" id="file">'+

以及如果文件大小大于 X 或其格式不受支持时如何提醒

【问题讨论】:

    标签: javascript php jquery ajax upload


    【解决方案1】:

    您需要将输入文件设置为多个以便能够选择多个文件。

    您还需要在选择文件时迭代文件,并监听输入的更改事件以便能够读取该文件。

    我做了一个例子,希望对你有帮助。

    编辑

    这里你有你期望的工作代码,现在你可以动态创建输入。

    $(document).ready(function(){
        	// let's encapsulate the code to prevent its exposeness in the window scope that is accessible from console developer tools
          // soe let's make a autoexec function, and let's declare all our login inside
          
          // the ($) code will get the object injected at the bottom of the function
        	(function($){
          	// our counter images uploaded
          	var imagesUploaded = [];
            // our limit to be reached
            var limitToBeReachedToEnableTheForm = 0;
            
            // reference to our btnSubmit
          	var btnSubmit = $("#myBtnSender");
            // reference to our form
            var form = $("#MyForm");
            // let's save reference for each input file
            var picker = $(".file-picker");
            var blockWrapper = $(".wrap-block");
            var addBlockBtn = $("#add-picker-block");
            var blockId = "block-id-";
            
            // let's listen for picker (change) event for each input file
            function onHandleFile(event) {
            	// get the file
              var file = event.target.files;
              // get the only file inside of the collection files
              file = file[0];
              var fileId = $(this).attr("id");
              
              // let's make sure file is actually an image, so we need to define what format of images we will allow
              var allowImagesTypes = ["image/jpg","image/gif", "image/png", "image/jpeg"];
             var imageType = file.type;
             
             // if the current image type is not supported, just abort the process and notify to user
             if (allowImagesTypes.indexOf(imageType) === -1) {
             		var messageAllowedTypes = allowImagesTypes.join(", ");
             		alert("Error, we only support these types of images : " + messageAllowedTypes);
                return false;
             }
             
             // if the current type image is allowed so let's get the title, caption and let's upload the image
             var currentPicker = $(this);
             var parentPickerBlock = currentPicker.parent(".block-image-picker");
             var title = parentPickerBlock.find('.image-title');
             title = title.length > 0 ? $.trim(title.val()) : "";
             var caption = parentPickerBlock.find('.image-caption');
             caption = caption.length > 0 ? $.trim(caption.val()) : "";
             
             uploadImage(title, caption, file, parentPickerBlock, fileId);
            };
    
            form.submit(function(){
              // if imagesUploaded is less than limitToBeReachedToEnableTheForm, so there are images to be upload and not allow the submittion of the form
              if (imagesUploaded.length < limitToBeReachedToEnableTheForm) {
        	      return false;
              }
              alert("Your form will send :D");
              return true;
            });
            
            addBlockBtn.on("click", addNewBlock);
            
        		function checkTotalImagesUploaded(fileId) {
            	if (fileId) {
              	imagesUploaded.push(fileId);
              }
              
              // if the 5 images were uploaded so enabled the submit button
              checkUploadsToEnableSubmitButton();
            }
            
            function checkUploadsToEnableSubmitButton() {
    	        if (imagesUploaded.length === limitToBeReachedToEnableTheForm) {
              	btnSubmit.removeAttr("disabled");
              } else {
              	btnSubmit.attr("disabled", "disabled");
              }
            }
            
    				function removeImageUploadedCounterIfExists(fileId) {
            		var index = imagesUploaded.indexOf(fileId)
            		if (index > -1) {
                	imagesUploaded.splice(index, 1);
                }
            }
            
            function addNewBlock() {
            	// Create the block inputs elements
            	var blockImagePicker = $("<div class='block-image-picker'>");
              var inputTitle = $("<input type='text' name='imageTitle[]' class='image-title' placeholder='Your image title' />");
              var inputFile = $("<input type='file' name='images[]' class='file-picker' />");
              // generate timestamp of creation
              var fileId = new Date() * 1;
              inputFile.attr("id", fileId);
              // put into the blockImagePicker
              blockImagePicker.append(inputTitle);
              blockImagePicker.append(inputFile);
              // add to block wrapper
              blockWrapper.append(blockImagePicker);
              // increment our limit counter
              limitToBeReachedToEnableTheForm++;
              // add data-id attribute
    					blockImagePicker.attr("id", blockId + limitToBeReachedToEnableTheForm);
              if (limitToBeReachedToEnableTheForm > 1) {
    						var removeBtn = $("<button>Remove</button>");
    	          blockImagePicker.append(removeBtn);
                removeBtn.data("container-id", blockId + limitToBeReachedToEnableTheForm);
    						removeBtn.on("click", onRemoveBlockPicker);
              }
              // add event listener to file picker
              inputFile.on("change", onHandleFile);
              checkUploadsToEnableSubmitButton();
            }
            
    				function onRemoveBlockPicker(event) {
            	event.preventDefault();
            	// get input file to remove eventListener
              var filePickerReference = $(this).prev();
              var fileId = filePickerReference.attr("id");
              // remove event listener
              filePickerReference.off("change");
              // get block id for current block
              var containerId = $(this).data("container-id");
              var containerBlock = $("#"+containerId);
              containerBlock.remove();
              limitToBeReachedToEnableTheForm--;
              removeImageUploadedCounterIfExists(fileId);
              checkUploadsToEnableSubmitButton();
            }
            
            function uploadImage(title, caption, file, parent, fileId) {
              var formData = new FormData();
              formData.append("title", title);
              formData.append("caption", caption);
              formData.append("image", file);
              var loader = $("<div>");
    
              $.ajax({
                url: 'http://my-url-endpoint-rest',
                data: formData,
                type: 'POST',
                contentType: false,
                processData: false,
                beforeSend: function() {
                	//beforeSend the image to upload, let's show the user what is happening
                  loader.text("Uploading " + file.name + " ...");
                  parent.append(loader);
                },
                success: function(response) {
                  // if the image was uploaded so increment our counter imagesUploaded
                  checkTotalImagesUploaded(fileId);
                },
                error: function(jqXHR, textStatus, errorMessage) {
                	// show some error if something was wrong
                  console.log("error", errorMessage); // Optional
                  alert("Error uploading the image " + file.name);
                },
                complete: function() {
        					// remove the loader, not matter if the response was wrong or good
                  loader.remove();
                }
              });
            }
            
            // create our first block when page is loaded
            addNewBlock();
          })($);
          // the ($) code above will inject the jQuery object into the closure
        });
    .block-image-picker {
      border: 1px solid blue;
      margin-bottom: 5px;
      padding: 5px;
    }
    
    .block-image-picker input {
      display: inline-block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <form id="MyForm">
          <div class="file-pickers-wrapper">
            <div class="wrap-block">
            </div>
            
            <div class="controls">
              <button id="add-picker-block">
              add new field
              </button>
            </div>
          </div>
    
          <button type="submit" id="myBtnSender" disabled="disabled">
            Send data
          </button>
        </form>

    【讨论】:

    • 非常感谢,但我希望文件输入只上传一张图片,像这样
    • 表单包含标题和5张带标题的图片,一旦我选择图片而不点击上传,我想开始上传,并且不提交主表单,并且在上传图片之前无法提交表单
    • @afm7 所以你需要上传 5 张图片,每张图片都有一个标题和一个标题字段,对吗?标题和标题是必需的还是可以是空的?,所以当你选择了5张图片时,你只需要选择图片吗?或者以您选择应该上传的每张图片的方式,当您上传了 5 张图片时,您可以在那里提交主表单,是吗?
    • @afm7 我只是编辑我的答案以添加你需要的工作代码,我希望它可以帮助你很多:D
    • 谢谢它帮助我,如果我希望它是无限的而不仅仅是 5
    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 2017-05-25
    相关资源
    最近更新 更多