6

How can I send a file with vue.js?

The following code is not working for me:

<span title="Upload" class="badge badge-info">
            <input type="file" id="file" name="file" @change="uploadData" class="archive" > <i id="iarchive" class="fa fa-upload"></i> 
</span>

When I make console.log(this.request.file) I get FILE [object File].

Here is the .js:

  uploadData: function(e) {
                var files = e.target.files[0];


                this.request.action = 'upload';
                this.request.file = files;
                console.log("FILE "+this.request.file);

                this.$http.post('data/getData.php', {
                data: this.request,    
                headers: {
                           'Content-Type': 'multipart/form-data'                   
                }
              }
               ).then(function(response) {

                    console.log("RESPONSE: "+response.body);

            }, function(response) {

                alert("error");
            });
            return false;
        }

But in PHP, I can't get the file, the response is :{} No properties.

PHP code:

$request = json_decode(file_get_contents('php://input')); 
$req = $request->data;
echo json_encode($req->file)

2 Answers 2

7

Add ref attribute to input:

<input ref="file-input" .../>

In controller you should write action:

uploadFile: function () {
  // try to log $refs object for deep understanding
  let fileToUpload = this.$refs.fileInput.files[0];
  let formData = new FormData();

  formData.append('fileToUpload', fileToUpload);
  this.$http.post ( 'data/getData.php', formData ).then(function () {
    // success actions
  });
}    

In php endpoint your uploaded files will be in form request object.

Sign up to request clarification or add additional context in comments.

2 Comments

thank for you response, but, now i get :null from php in $request = json_decode(file_get_contents('php://input')); var_dump($request); | imgur.com/Dw0XwpU, how recive this file in php?
Try to dump $_FILES, official doc
0

Use FormData append() function:

var files = e.target.files[0];

var formData = new FormData();
formData.append('file', files);

this.$http.post('/data/getData.php', formData, {
   headers: {
        'Content-Type': 'multipart/form-data'
   }
})

2 Comments

thank for you response, but, now i get :null from php in $request = json_decode(file_get_contents('php://input')); var_dump($request); | imgur.com/Dw0XwpU
use $_FILES. I see you solved the problem, good luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.