복붙노트

[JQUERY] Ajax를 사용하여 하나 개의 형태로 데이터 및 파일을 업로드?

JQUERY

Ajax를 사용하여 하나 개의 형태로 데이터 및 파일을 업로드?

해결법


  1. 1.내가 가진 문제는 잘못된 jQuery를 식별자를 사용했다.

    내가 가진 문제는 잘못된 jQuery를 식별자를 사용했다.

    당신은 하나 개의 형태가 아약스를 사용하여 데이터와 파일을 업로드 할 수 있습니다.

    PHP + HTML

    <?php
    
    print_r($_POST);
    print_r($_FILES);
    ?>
    
    <form id="data" method="post" enctype="multipart/form-data">
        <input type="text" name="first" value="Bob" />
        <input type="text" name="middle" value="James" />
        <input type="text" name="last" value="Smith" />
        <input name="image" type="file" />
        <button>Submit</button>
    </form>
    

    jQuery를 + 아약스

    $("form#data").submit(function(e) {
        e.preventDefault();    
        var formData = new FormData(this);
    
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            data: formData,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
    

    짧은 버전

    $("form#data").submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);    
    
        $.post($(this).attr("action"), formData, function(data) {
            alert(data);
        });
    });
    

  2. 2.또 다른 옵션은 iframe을 사용하고 폼의 목표를 설정하는 것입니다.

    또 다른 옵션은 iframe을 사용하고 폼의 목표를 설정하는 것입니다.

    당신은 (는 jQuery를 사용)이 시도 할 수 있습니다 :

    function ajax_form($form, on_complete)
    {
        var iframe;
    
        if (!$form.attr('target'))
        {
            //create a unique iframe for the form
            iframe = $("<iframe></iframe>").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body'));
            $form.attr('target', iframe.attr('name'));
        }
    
        if (on_complete)
        {
            iframe = iframe || $('iframe[name="' + $form.attr('target') + '"]');
            iframe.load(function ()
            {
                //get the server response
                var response = iframe.contents().find('body').text();
                on_complete(response);
            });
        }
    }
    

    그것은 당신이 직렬화 필요하거나 데이터를 준비하지 않는, 모든 브라우저에서 잘 작동합니다. 하나의 아래쪽은 진행 상황을 모니터 할 수 없다는 것입니다.

    또한, 크롬에 대한 최소한 요청은 개발자 도구의 "XHR"탭이 아니라 "문서"아래에 표시되지 않습니다


  3. 3.나는 HttpPostedFilebase로 대신 내가 몇 가지 물건을 할 필요가 위치를 클릭 버튼을 사용하는 데 필요한 제출에 양식을 사용하고, 그래서 여기에 양식을 제출하는 모든 확인을 경우 내가 일하고 그것을 가지고 어떻게 ASP.Net MVC에서이 같은 문제가 발생했다

    나는 HttpPostedFilebase로 대신 내가 몇 가지 물건을 할 필요가 위치를 클릭 버튼을 사용하는 데 필요한 제출에 양식을 사용하고, 그래서 여기에 양식을 제출하는 모든 확인을 경우 내가 일하고 그것을 가지고 어떻게 ASP.Net MVC에서이 같은 문제가 발생했다

    $(".submitbtn").on("click", function(e) {
    
        var form = $("#Form");
    
        // you can't pass Jquery form it has to be javascript form object
        var formData = new FormData(form[0]);
    
        //if you only need to upload files then 
        //Grab the File upload control and append each file manually to FormData
        //var files = form.find("#fileupload")[0].files;
    
        //$.each(files, function() {
        //  var file = $(this);
        //  formData.append(file[0].name, file[0]);
        //});
    
        if ($(form).valid()) {
            $.ajax({
                type: "POST",
                url: $(form).prop("action"),
                //dataType: 'json', //not sure but works for me without this
                data: formData,
                contentType: false, //this is requireded please see answers above
                processData: false, //this is requireded please see answers above
                //cache: false, //not sure but works for me without this
                error   : ErrorHandler,
                success : successHandler
            });
        }
    });
    

    이 뜻이 제대로 MVC 모델을 채우는 것보다, 모델, HttpPostedFileBase의 속성 [에 있는지 확인하시기 바랍니다] HTML 즉의 입력 컨트롤의 이름과 동일한 이름을 가진

    <input id="fileupload" type="file" name="UploadedFiles" multiple>
    
    public class MyViewModel
    {
        public HttpPostedFileBase[] UploadedFiles { get; set; }
    }
    

  4. 4.이하 :

    이하 :

    $("form#data").submit(function() {
        var formData = new FormData(this);
        $.post($(this).attr("action"), formData, function() {
            // success    
        });
        return false;
    });
    

  5. 5.나를 위해, 그것은에 enctype없이 작동하지 않았다 : Ajax 요청에 '다중 / 폼 데이터'필드. 나는 비슷한 문제에 붙어있는 사람을 도움이되기를 바랍니다.

    나를 위해, 그것은에 enctype없이 작동하지 않았다 : Ajax 요청에 '다중 / 폼 데이터'필드. 나는 비슷한 문제에 붙어있는 사람을 도움이되기를 바랍니다.

    에 enctype이 이미 양식 속성에 설정되어 있지만, 어떤 이유로, Ajax 요청이 자동으로 명시 적 선언 (jQuery를 3.3.1)없이 PHP 버전을 확인하지 않았다.

    // Tested, this works for me (jQuery 3.3.1)
    
    fileUploadForm.submit(function (e) {   
        e.preventDefault();
        $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                enctype: 'multipart/form-data',
                data: new FormData(this),
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log('Thank God it worked!');
                }
            }
        );
    });
    
    // enctype field was set in the form but Ajax request didn't set it by default.
    
    <form action="process/file-upload" enctype="multipart/form-data" method="post" >
    
         <input type="file" name="input-file" accept="text/plain" required> 
         ...
    </form>
    

    다른 사람이 위에서 언급 한 바와 같이, 또한 contentType이와 processData 분야에 특별한주의를 지불하십시오.


  6. 6.나를 위해 코드가 작동 다음

    나를 위해 코드가 작동 다음

    $(function () {
        debugger;
        document.getElementById("FormId").addEventListener("submit", function (e) {
            debugger;
            if (ValidDateFrom()) { // Check Validation 
                var form = e.target;
                if (form.getAttribute("enctype") === "multipart/form-data") {
                    debugger;
                    if (form.dataset.ajax) {
                        e.preventDefault();
                        e.stopImmediatePropagation();
                        var xhr = new XMLHttpRequest();
                        xhr.open(form.method, form.action);
                        xhr.onreadystatechange = function (result) {
                            debugger;
                            if (xhr.readyState == 4 && xhr.status == 200) {
                                debugger;
                                var responseData = JSON.parse(xhr.responseText);
                                SuccessMethod(responseData); // Redirect to your Success method 
                            }
                        };
                        xhr.send(new FormData(form));
                    }
                }
            }
        }, true);
    });
    

    액션 포스트 방법에서, HttpPostedFileBase을 UploadFile로 매개 변수를 전달하고 작업 방법의 당신의 매개 변수에 언급 한 바와 같이 확인 파일 입력이 동일있다합니다. 그것은뿐만 아니라 양식을 시작 AJAX와 함께 작동합니다.

    당신의 AJAX 당신이 게시물 전화가 위에서 언급 한 코드에 정의하기 때문에 양식이 여기에 작동하지 않습니다 BEGIN 것을 여기에 기억하고 당신은 요구 사항에 따라 코드에 방법을 참조 할 수 있습니다

    나는 말에 대답하고 알고 있지만, 이것은 나를 위해 일한 것입니다


  7. 7.단순하지만 더 효과적인 방법 : 새로운 FormData ()는 용기 (또는 가방)처럼 그 자체입니다. 당신은 그 자체로 모든 것을 ATTR 또는 파일을 넣을 수 있습니다. 유일한 것은 당신이 속성, 파일을 추가해야합니다, fileName에 예를 들면 :

    단순하지만 더 효과적인 방법 : 새로운 FormData ()는 용기 (또는 가방)처럼 그 자체입니다. 당신은 그 자체로 모든 것을 ATTR 또는 파일을 넣을 수 있습니다. 유일한 것은 당신이 속성, 파일을 추가해야합니다, fileName에 예를 들면 :

    let formData = new FormData()
    formData.append('input', input.files[0], input.files[0].name)
    

    그냥 AJAX 요청에 전달합니다. 예 :

        let formData = new FormData()
        var d = $('#fileid')[0].files[0]
    
        formData.append('fileid', d);
        formData.append('inputname', value);
    
        $.ajax({
            url: '/yourroute',
            method: 'POST',
            contentType: false,
            processData: false,
            data: formData,
            success: function(res){
                console.log('successfully')
            },
            error: function(){
                console.log('error')
            }
        })
    

    당신은 FormData와 파일이나 데이터의 N 번호를 추가 할 수 있습니다.

    당신은 Node.js를 국도 파일에 Script.js 파일에서 AJAX 요청을하는 경우와 사용에주의 데이터에 액세스 req.body (즉, 텍스트) 액세스 파일 (예 : 이미지, 동영상 등)에 req.files


  8. 8.당신은, 당신의 formdata에 그들을 추가이 읽을 수 it.you에서 파일 및 datas를 추가 할 수 있습니다 ..

    당신은, 당신의 formdata에 그들을 추가이 읽을 수 it.you에서 파일 및 datas를 추가 할 수 있습니다 ..

    https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

    더 잘 이해합니다. 별도로 그들에게 파일에 대한 $ _FILES 및 데이터에 대한 $ _POST를 검색 할 수 있습니다.


  9. 9.내 경우에는 내가 헤더를 통해 정보 보냈습니다 있었고, 또한 파일이 FormData 객체를 사용하여 보낸 POST 요청을했습니다.

    내 경우에는 내가 헤더를 통해 정보 보냈습니다 있었고, 또한 파일이 FormData 객체를 사용하여 보낸 POST 요청을했습니다.

    나는 그것이, 여기에 몇 가지 답변의 조합을 사용하여 작업을했다 그래서 기본적으로 최대의 작업 내 Ajax 요청이 다섯 줄을 가졌다 종료 무엇을 :

     contentType: "application/octet-stream",
     enctype: 'multipart/form-data',
     contentType: false,
     processData: false,
     data: formData,
    

    어디 formData는 다음과 같이 생성 된 변수했다 :

     var file = document.getElementById('uploadedFile').files[0];
     var form = $('form')[0];
     var formData = new FormData(form);
     formData.append("File", file);
    

  10. 10.

    <form id="form" method="post" action="otherpage.php" enctype="multipart/form-data">
        <input type="text" name="first" value="Bob" />
        <input type="text" name="middle" value="James" />
        <input type="text" name="last" value="Smith" />
        <input name="image" type="file" />
        <button type='button' id='submit_btn'>Submit</button>
    </form>
    
    <script>
    $(document).on("click", "#submit_btn", function (e) {
        //Prevent Instant Click  
        e.preventDefault();
        // Create an FormData object 
        var formData = $("#form").submit(function (e) {
            return;
        });
        //formData[0] contain form data only 
        // You can directly make object via using form id but it require all ajax operation inside $("form").submit(<!-- Ajax Here   -->)
        var formData = new FormData(formData[0]);
        $.ajax({
            url: $('#form').attr('action'),
            type: 'POST',
            data: formData,
            success: function (response) {
                console.log(response);
            },
            contentType: false,
            processData: false,
            cache: false
        });
        return false;
    });
    </script>
    
    

    ///// otherpage.php

    <?php
        print_r($_FILES);
    ?>
    
  11. from https://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax by cc-by-sa and MIT license