weixin_33726318 2016-01-21 19:03 采纳率: 0%
浏览 19

通过AJAX上传文件输入

While filling the form, I want my users to have a preview on what they just selected in the file input field. For this, I'm trying to avoid any kind of plugin or additional software (except for jQuery).

This is what I got, after some internet research:

    $("#file-upload").change(function() {
    var formData = new FormData($("#editForm")[0]);
    $.ajax({
        url: 'script.php',  //Server script to process data
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            return myXhr;
        },
        //Ajax events
        success: function(output) {
            document.write(output);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        },
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});

The problem with this: formData does not contain any input fields with type="file"!

Any help is appreciated :)

  • 写回答

1条回答 默认 最新

  • weixin_33724059 2016-01-21 19:16
    关注

    This works for me:

    <input type="file" name="browseFile" id="photo" placeholder="File" />
    <input id="userId" type="text" />
    
    <input type="submit" value="create request" onclick="CreateRequest(event)" 
    
    
    <script>
          function CreateRequest(event) {
                event.preventDefault ? event.preventDefault() : event.returnValue = false;
    
                var inputFilePhoto = document.getElementById("photo");
                var imageFile = inputFilePhoto.files[0];
    
                var userId = document.getElementById("userId").value;
    
    
                var formData = new FormData();             
                formData.append("RequestPhoto", imageFile);
                formData.append("UserId", userId);
    
                $.ajax({
                    type: "POST",
                    url: "/User/CreateRequest",
                    data: formData,
                    contentType: false,
                    processData: false,
    
                    success: function () {
                        alert("OK");
                    },
                    error: function () {
                        alert("Error");
                    }
    
                });
    
    评论

报告相同问题?