如何从HTML字段中提取文件数据并以JSON格式传输?

时间:2017-01-09 08:39:45

标签: jquery json

我有两个文件字段,我从表单中提取:

  1. 单个文件(floorimage)
  2. 多个文件选择(imageFiles)
  3. 选择文件后,我想将文件数据转换为base64 encoded字符串和JSON,如下所示,但我不知道该怎么做。

    这是我到目前为止所做的。

    {
    "floorimage" : "/9j/4QtyRXhpZgAATU0AKgAAAAgADAEAA.....",   // base64 encoded string image value
    "imageFiles" : ["/9j/4QtyRXhpZgAATU0AKgAAAAgADAEAA....."], // base64 encoded string image value
    }

    $(document).ready(function() {
    
        $("#multible_btn").click(function() {
    
            // Single Image Start
    
            var filesSelected = document.getElementById("floorplan_img").files;
                if (filesSelected.length > 0) {
                  var fileToLoad = filesSelected[0];
    
                  var fileReader = new FileReader();
    
                  fileReader.onload = function(fileLoadedEvent) {
                    floor_image_base = fileLoadedEvent.target.result; 
                    var base64 = floor_image_base ;
                     var str = base64;
                     var arr = str.split(",");
                     var floor_image = arr[1] ;
                    data.floorimage = floor_image;// g
                  }
                  fileReader.readAsDataURL(fileToLoad);
            }
    
            // Single Image End
    
            // Multiple Image Start            
    
            var filesSelected = document.getElementById("upload_properties").files;
            if (filesSelected.length > 0) {
              var fileToLoad = filesSelected[0];
              var fileReader = new FileReader();
              fileReader.onload = function(fileLoadedEvent) {
                property_image_base = fileLoadedEvent.target.result;
                 var base641 = property_image_base ;
                 var str1 = base641;
                 var arr1 = str1.split(",");
                 var property_image = arr1[1] ;
                 data.imageFiles=property_image; // g
              }
              fileReader.readAsDataURL(fileToLoad);
            }
    
            // Multiple Image End
    
            var data = {
                "floorimage" :"",
                "imageFiles" :"",
            }
    
            console.log(data);
    
        });
    });
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <form>
      Single images: <input type="file" name="img" id="floorplan_img"> <br><br>
      Multiple images: <input type="file" name="img" id="upload_properties" multiple>
    
      <input type="button" id="multible_btn" value="submit">
    </form>
    

0 个答案:

没有答案