将文件上传到 html 输入时如何自动加载?

当我将文件放入 html 输入中时,我想通过 ajax post 上传。(无需点击)它在我单击当前代码中的启动按钮后起作用。我的代码


    $(document).ready(function () {

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

    $('#img-loag-scrin').html('');

    $('div#img-loag-scrin').css('display', 'block').prepend('<img id="img_akb" src="https://' + HTTP + '/images/ajax-loader.gif" id="buff-load" style="display:block;margin:10px auto; cursor: wait;">');

    var fd = new FormData();

    var files = $('#file')[0].files[0];

    fd.append('file', files);

    $.ajax({

      url: 'https://localhost.uz/ajax/ajax_img.php?act=upload',

      dataType: "json",

      type: 'post',

      cache: false,

      data: fd,

      contentType: false,

      processData: false,

      success: function (response) {

        if (response != 0) {

          $('#img-loag-scrin').prepend(response.scrins);

          $('#textrea').val($('#textrea').val() + " " + response.textrea);

          $('#img_akb').remove();

        } else {

          alert('File not uploaded');

        }

      }

    });

  });

});

HTML代码


<form method="post" action="" enctype="multipart/form-data" id="myform">

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

  <input type="button" class="sf_button" value="Upload" id="but_upload">

</form>

当 html 插入到输入文件中时,无需单击按钮,就应该加载该文件。加载图像后,图像必须从输入中消失


繁星点点滴滴
浏览 54回答 1
1回答

慕侠2389804

我用过改变。$(document).ready(function () {&nbsp; $('#file').unbind().on('change', function () {&nbsp; &nbsp; $('#img-loag-scrin').html('');&nbsp; &nbsp; $('div#img-loag-scrin').css('display', 'block').prepend('<img id="img_akb" src="https://' + HTTP + '/images/ajax-loader.gif" id="buff-load" style="display:block;margin:10px auto; cursor: wait;">');&nbsp; &nbsp; var fd = new FormData();&nbsp; &nbsp; var files = $('#file')[0].files[0];&nbsp; &nbsp; fd.append('file', files);&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; url: 'https://localhost/ajax/ajax_img.php?act=upload',&nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; type: 'post',&nbsp; &nbsp; &nbsp; cache: false,&nbsp; &nbsp; &nbsp; data: fd,&nbsp; &nbsp; &nbsp; contentType: false,&nbsp; &nbsp; &nbsp; processData: false,&nbsp; &nbsp; &nbsp; success: function (response) {&nbsp; &nbsp; &nbsp; &nbsp; if (response != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#img-loag-scrin').prepend(response.scrins);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#textrea').val($('#textrea').val() + " " + response.textrea);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#img_akb').remove();&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('File not uploaded');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; });});html代码<form method="post" action="" enctype="multipart/form-data" id="myform">&nbsp; &nbsp;<input type="file" id="file" name="file"></form>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5