如何用ajax发布文件?

Trying to save a file to a db. I am using formData via javascript to append the file and adding this as a post object via ajax. for some reason nothing gets sent.

What am I doing wrong?

HTML

<input type="file" style="display: none;" class="btn btn-primary uploadFile">

script:

        $(".saveImage")
            .on("click",
                function() {
                  var files = $(".uploadFile");
                  var data = new FormData();


                  data = $.OverWatch.worker.uploadFileHandler.addUploadFiles(files, data);


                    $.OverWatch.worker.postUserData("/Administration/AddUserImage", data, function () {
                        alert("done");
                    });

                });

Functions above look like:

        addUploadFiles: function (files, data) {
            $.each(files, function (i, v) {
                var file = $(this).data("files");
                data.append("file", file);
            });

            return data;
        }

postUserData:

    postUserData: function(url, data, callback) {

        $.LoadingOverlay("show");
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            cache: false,
            processData: false,
            contentType: false,
            dataType: "HTML",
            success: function(data) {

                if (callback) {
                    callback(data);
                    $.LoadingOverlay("hide");
                }

            },
            error: function(event, jqxhr, settings, thrownError) {
                //$.helpers.errorHandler($("#fileDialogErrors"), event.responseText);
                var h;
                $.LoadingOverlay("hide");
            }
        });
    },

backend:

    public ActionResult AddUserImage()
    {
        if (Request.Files.Count != 0)
        {
           //save
        }

        return null;
    }

edit:

 var files = $(".uploadFile");

returns:

enter image description here

查看全部
weixin_33698823
weixin_33698823
2017/04/06 00:04
  • file
  • ajax
  • javascript
  • jquery
  • 点赞
  • 收藏
  • 回答
    私信

3个回复