js upload pictures, preview

I just opened blog, I would not be like those who wrote so much trouble, I'll pick dry do, achieve function

1. First need to put this div onto the page, pick a style to find the front click on ok 

<label for="requirement" class="col-md-3 control-label span3">图片上传</label>
<div class="col-md-9">
<div class="input-group">
  <input id="photoCover" class="form-control" readonly type="text">
  <label class="input-group-btn">
    <input id="file" type="file" name="file" style="left: -9999px; position: absolute;">
    <span class="btn btn-default">Browse</span>
  </label>
</div>
</div>

2. The second is to give this id = "file" registration click event, the so-called select a picture, browse pictures

$("#file").change(function (e) {
  var file = e.target.files[0] || e.dataTransfer.files[0];
  $('#photoCover').val(document.getElementById("file").files[0].name);
  if (file) {
    var reader = new FileReader();
    reader.onload = function () {
      $("img").attr("src", this.result);
    }

    reader.readAsDataURL(file);
  }
});

3. The picture is saved request, of course, there are some parameters need to work together, just behind the stitching on the line formdata

function save(){
  var id = $("#id").val().trim();
  var file = document.getElementById("file").files[0];
  var formData = new FormData();
  formData.append('id', id);
  formData.append('file', file);

  $.ajax({
    url: "/home/about",
    type: "post",
    data: formData,
    contentType: false,
    processData: false,
    mimeType: "multipart/form-data",
    success: function (data) {
    
    },
    error: function (data) {
    
    }
  });
}

I think you can, I will always put my experience better, write to everyone here, thank you

Guess you like

Origin www.cnblogs.com/cleargood/p/11080837.html