2

I have a simple upload file in my html like so:

<div class="col-md-12">
    <span id="fileUploadErr">Please Upload A File!</span>
    <div  style="margin-bottom: 10px;"></div>
    <input id="pickUpFileAttachment" type="file" name="attachFileObj" size="60" />
</div>

When I click on the "Submit" button the following action occurs:

$("form").submit(function() {
    event.preventDefault();

    var assignmentObj1 = {

        selectionId: trDataSecondTable.selectionId,
        inout: "in",
        letterReceivedBy: $("#letterReceivedBy").val(),
        letterIssuedSubBy: $("#letterIssuedSubBy").val(),
        representativeNameEng: $("#representativeNameEng").val(),

        letterId: 2,
        assessmentNo: 0
        imageFile: $("#representativeNameEng").val()
        imageTitle:
    }

    console.log(jsonData);
    $.ajax({

        url: A_PAGE_CONTEXT_PATH + "/form/api/saveProcessAnexTwo",
        method: "post",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify(assignmentObj1),
        success: function(response) {

        },
        error: function(response) {
            switch (response.status) {
                case 409:
                    alert("error");
            }
        }
    });
});

I need to assign the fileName and the uploaded file while sending from AJAX and need to put it inside the assignmentObj1 variable so I tried: imageFile: $("#representativeNameEng").val() to get the file information but it is not coming. How can I get the file information and send from AJAX by putting it in a local variable? And also how can I get the name of the file which can be placed in the imageTitle: property?

julianstark999
  • 3,450
  • 1
  • 27
  • 41
ashwin karki
  • 643
  • 5
  • 19
  • 35

2 Answers2

1

Easiest method is to use formData to send data:

var data = new FormData();
$.each($('#filecontainer')[0].files, function(i, file) {
   data.append('file-'+i, file);
});

So now you have formData object

$.ajax({
   url: 'php/upload.php',
   data: data,
   cache: false,
   contentType: false,
   processData: false,
   method: 'POST',
   type: 'POST', // For jQuery < 1.9
   success: function(data){
      alert(data);
   }
});

Hope this helps.

kshitij
  • 642
  • 9
  • 17
1

This is how to deal with the file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jquery Ajax File Upload</title>
</head>
<body>

<div class="col-md-12">
   <span id="fileUploadErr">Please Upload A File!</span>
   <div  style="margin-bottom: 10px;"></div>
   <input id="pickUpFileAttachment" type="file" name="pickUpFileAttachment" size="60" />
</div>
    
    <div class="result"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
   
   //  $("form").submit(function(){
    
        $('#pickUpFileAttachment').change(function(e){
          var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]); 
           
         
            $.ajax({
                url : window.location.pathname + "/form/api/saveProcessAnexTwo",
             data: formData,
    type: 'POST',
    contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
    processData: false, 
                success: function(response){
                 alert("suc");
                    $('.result').html(response.html)
                    
                } , error: function(response){
                        switch(response.status){
                            case 409:
                            alert("error");
                        }}
            });
        });
        //});
    });
    </script>
</body>
</html>
I_Al-thamary
  • 3,385
  • 2
  • 24
  • 37
  • can't i assign formData to imageFile: inside of that variable? – ashwin karki Dec 04 '18 at 08:46
  • @ashwinkarki you need to convert the Image to Base64 String and then to JSON Object.https://stackoverflow.com/questions/41357655/image-to-base64-string-to-json-object https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – I_Al-thamary Dec 04 '18 at 08:50
  • how is that function getBase64(file) called? can u please add the converting the code into base64 please? – ashwin karki Dec 04 '18 at 08:55
  • @ashwinkarki look at this example:https://stackoverflow.com/questions/34779799/upload-base64-image-with-ajax – I_Al-thamary Dec 04 '18 at 09:00
  • @ashwinkarki this the code maybe will help you to undrstand :https://ourcodeworld.com/articles/read/322/how-to-convert-a-base64-image-into-a-image-file-and-upload-it-with-an-asynchronous-form-using-jquery – I_Al-thamary Dec 04 '18 at 09:02
  • @ashwinkarki https://ourcodeworld.com/articles/read/76/how-to-save-a-base64-image-from-javascript-with-php – I_Al-thamary Dec 04 '18 at 09:07
  • i am not php developer i am not getting the codes of php sorry – ashwin karki Dec 04 '18 at 09:08