weixin_33711641 2018-02-23 18:28 采纳率: 0%
浏览 29

Ajax文件上传

Im trying to submit a form that has a file input via ajax. I have a few important things that need to happen.

  1. The file input should be triggered by a button (done)
  2. The form should be submitted when a file has been selected (done)
  3. The page should NOT refresh and I should be able to check the result in the standard ajax fashion.

I have tried to do this myself, but nothing I find fits my needs.

The user needs to see a button like this, instead of the standard form input:

button

I have used the following code:

        <form id="uploadProfilePictureForm" action="" method="post" enctype="multipart/form-data" style="display: none">
            <input name="uploadProfilePicture" id="uploadProfilePicture" type="file" onchange="this.form.submit()" style="display: none;"/>
        </form>
        <a id="changeProfileButtonIcon" class="btn btn-info float-right mx-0 my-0">Change (in progress)</a>


          <script>
            $("#changeProfileButtonIcon").on('click', function(e){
            e.preventDefault();
            $("#uploadProfilePicture:hidden").trigger('click');
             });
          </script>

This opens the input correctly, and if I have the action set to my upload page, the image is uploaded when the select dialog is closed and then I just see a white page with my success message (as expected)

Because I don't want a page refresh I have attempted to do this via jQuery:

$("#uploadProfilePictureForm").on('submit',(function(e) {
            e.preventDefault();
            $.ajax({
                url: "/helpers/upload_image.php", // Url to which the request is send
                type: "POST",             // Type of request to be send, called as method
                data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                contentType: false,       // The content type used when sending data to the server.
                cache: false,             // To unable request pages to be cached
                processData: false,        // To send DOMDocument or non processed data file it is set to false
                success: function (data)   // A function to be called if request succeeds
                {
                    var a = 1;
                }
            });
        }));

I placed a breakpoint on the line "preventDefault" and also on the "var a = 1" none of these get triggered and the page just refreshes.

Can anyone help me?

Thanks

  • 写回答

1条回答 默认 最新

  • weixin_33701251 2018-02-23 18:55
    关注

    You don't need a form if all you're doing is uploading (a) file(s). You method of having a button trigger a click on another button which triggers a click on a third thing is overly complicated.And you should not mix event attributes with event listeners.

    $("#realBtn").change(function(){
      var formData = new FormData();
      for(var i=this.files.length; i--;)
        formData.append('uploadProfilePicture[]', this.files[i], this.files[i].name);
      $.ajax({
          url: "/helpers/upload_image.php",
          type: "POST", 
          data: formData,
          contentType: false,
          cache: false,
          processData: false,
          success: function (data){
              console.log("upload complete");
          }
      });
    });
    
    // Trigger the real file upload button
    $("#fakeBtn").click(()=>$("#realBtn").click());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input id="realBtn" type="file" style="display: none;" />
    <input id="fakeBtn" type="button" value='click to upload stuff'/>

    That said, you should take advantage of one of the many jQuery plugins that does all the dirty work for you, like this one, that I wrote.

    There are many reason you should use this instead...

    • it handles the upload part,
    • it lets you show the image preview while it's uploading,
    • it lets you see upload progress,
    • it supports drag and drop,
    • it's capable of only allowing a certain type of file (like images)
    • etc etc.

    $("#fileBtn").fileUpload({
      url: "/path/to/upload.php",
      accept: "image/gif, image/png, image/jpeg, .png, .gif, .jpg",
      change: function(){
        $("#preview").html("Loading...");
        $("#fileBtn").fileUpload("getDataURI", function(dataURI){
          $("#preview").html("<b>Your image: </b><br><img src='"+dataURI+"' />");
        }); 
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/Pamblam/fileUpload/master/fileUpload.js"></script>
    
    <div id=preview></div>
    <button id=fileBtn>click me</button>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名