1

My goal looks simple, but I try to upload a single file, asynchronously, using Vue.js (and axios, for instance). It seems to work as long as I don't try to handle the upload at server side. When I 'plug' my server code I get error 500 and no clue to find out what's going on.

My HTML :

<form action="#" enctype="multipart/form-data">
    <input type="file" name="files[]" v-on:change="onFileChange">
</form>

My Vue.js script :

onFileChange: function(event) {
  var image = new Image();
  var reader = new FileReader();

  reader.addEventListener('load', function(){
    console.log('file readed : ');

    axios.post('/upload_file', reader.result, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
});
reader.readAsDataURL(event.target.files[0]);

},

My Node.js server code :

router.post('/upload_file', function(req, res) {
  var form = new formidable.IncomingForm();
  form.IncomingForm().parse(req) // this line create Error #500
    .on('file', function(name, file) {
        console.log('Got file:', name);
    })
    .on('field', function(name, field) {
        console.log('Got a field:', name);
    })
    .on('error', function(err) {
        console.log('Got a error:');
        next(err);
    })
    .on('end', function() {
        res.end();
    });
  res.end();
});

I spent a day on this, file upload is just my nightmare, any help will be appreciated (and sorry for my english).

1 Answer 1

2

I'm not familiar with the node part. But in Vue I would do this:

onFileChange: function(event) {
    let reader = new FileReader();
    reader.readAsDataURL(event.target.files[0]);
    reader.addEventListener('load', function(data) {
    axios.post('/upload_file', {
        data: data.target.result
    });
});

So basically add "data" as parameter in die file readers event listener function and "data.target.result" to transfer the file data.

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

Comments

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.