0

I am trying to upload a file using the javascript formData object.

                                    var formData = new FormData(form[0]);
                                    formData.append('attachments[]', 
                                    localStorage.getItem('file_content'));
                                    $.ajax({
                                        url: form[0].action,
                                        type: "POST",
                                        enctype: 'multipart/form-data',
                                        processData: false,
                                        contentType: false,
                                        cache: false,
                                        data: formData,
                                        success: function(response){
                                            console.log(response);
                                        }
                                    });

So the local storage 'file_content' has the file content in blob format. The above code works, but the problem is that the file content is submitted as $_POST variable. I want the file to be submitted and available in the $_FILES server variable. Is it possible to do that. Please help.

Akhilesh
  • 1,243
  • 4
  • 16
  • 49
  • Read [this](https://stackoverflow.com/questions/19119040/how-do-i-save-and-restore-a-file-object-in-local-storage). You can't serialize a file object. – Chin. Udara May 21 '21 at 15:51
  • Cast blob to base64, if you want to sent it via ajax. The other case is to simple create a form to directly upload without local storage (unless it is necessary) Both cases have limitations on what you send. – gmastro May 21 '21 at 21:06
  • @gmastro Casting to base64 will make it available in $_FILES? Form file input doesn't allow to change the value programmatically due to security concerns. – Akhilesh May 24 '21 at 04:09
  • @Akhilesh Check your POST request. 1) Open console on your browser and see if the `attachment[]` parameter is in your request data 2) Add a server-side dump which will echo the request contents $_POST. If recall correctly, there will hardly be any data on $_FILES superglobal via ajax Without `attachments[]` param, then please check MDN USVString, Blob and FileReader and how to convert data into an acceptable format for FormData. Moreover, always try the simplest approach. Send the post directly and not via ajax. When you have it, use file_put_contents or whatever Symphony provides. – gmastro May 24 '21 at 20:46

1 Answers1

0

Try this code ....! Normaly, that must run !!

var myForm = $("#formid")[0]
var formdata = new FormData(myForm);
            $.post({url:"path/to/traitment", data:formdata, contentType:false, processData:false}, 
             function(data){
                // your code here ...
            }, 'json');

In your php file

var_dump($_FILES);
//for to check if that exist !
devaris21
  • 1
  • 1