How To Use FormData() For Uploading File In Vue












1















So I had asked a question previously, and got a little bit of help as far as logging the results however my results are not making sense.



So I have a input



<input type="file" name="import_file" v-on:change="selectedFile($event)">


The v-on:change binds the selected file to my data object this.file



selectedFile(event) {
this.file = event.target.files[0]
},


and then I submit the file with this method



uploadTodos() {
let formData = new FormData();
formData.append('file', this.file);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
this.$store.dispatch('uploadTodos', formData);
}


However when I submit it seems there is no data attached to formData because my logged result is this



file, [object File]


shouldn't I have my actual data appended to the formData object??



I have referenced other articles on how to post but I am not getting the desired results.



article 1
article2



uploadTodos(context, file) {
console.log(file)
axios.post('/import', file,{ headers: {
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log(response.data)
context.commit('importTodos', response.data)
})
.catch(error => {
console.log(error.response.data)
})
}


when I console.log(file) the formData object is empty



Backend Question
So my issue with Laravel on the backend is with the maatwebsite package. From what I have seen is the 3.0 version does not yet support imports. And the only work around suggested is to install version 2.0? Is this still the only workaround? Here is the controller method



public function importExcel(Request $request) 
{

if (empty($request->file('file')->getRealPath())) {
return back()->with('success','No file selected');
}
else {
$path = $request->file('file')->getRealPath();
$inserts = ;
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts = ['user_id' => $row['user_id'], 'todo' => $row['todo']];
};
}
});

if (!empty($inserts)) {
DB::table('todos')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}


return back();
}

}


The line not suppported by version 3.0 is this



Excel::load($path,function($reader) use (&$inserts)









share|improve this question

























  • A File encapsulates the data. developer.mozilla.org/en-US/docs/Web/API/File

    – Roy J
    Nov 26 '18 at 14:27











  • what exactly are you trying to achieve and what is the error you are having ?

    – Mazino S Ukah
    Nov 26 '18 at 14:35











  • @MazinoSUkah, I am trying to submit my form data object with the this.$store.dispatch('uploadTodos', formData);, however my vuex method uploadTodos contains no data. Please view updated question for vuex method

    – TJ Weems
    Nov 26 '18 at 14:38











  • @RoyJ, when I console.log(pair) it shows the contents of the formData object however once it reaches my vuex method it seems to be empty....

    – TJ Weems
    Nov 26 '18 at 14:40
















1















So I had asked a question previously, and got a little bit of help as far as logging the results however my results are not making sense.



So I have a input



<input type="file" name="import_file" v-on:change="selectedFile($event)">


The v-on:change binds the selected file to my data object this.file



selectedFile(event) {
this.file = event.target.files[0]
},


and then I submit the file with this method



uploadTodos() {
let formData = new FormData();
formData.append('file', this.file);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
this.$store.dispatch('uploadTodos', formData);
}


However when I submit it seems there is no data attached to formData because my logged result is this



file, [object File]


shouldn't I have my actual data appended to the formData object??



I have referenced other articles on how to post but I am not getting the desired results.



article 1
article2



uploadTodos(context, file) {
console.log(file)
axios.post('/import', file,{ headers: {
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log(response.data)
context.commit('importTodos', response.data)
})
.catch(error => {
console.log(error.response.data)
})
}


when I console.log(file) the formData object is empty



Backend Question
So my issue with Laravel on the backend is with the maatwebsite package. From what I have seen is the 3.0 version does not yet support imports. And the only work around suggested is to install version 2.0? Is this still the only workaround? Here is the controller method



public function importExcel(Request $request) 
{

if (empty($request->file('file')->getRealPath())) {
return back()->with('success','No file selected');
}
else {
$path = $request->file('file')->getRealPath();
$inserts = ;
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts = ['user_id' => $row['user_id'], 'todo' => $row['todo']];
};
}
});

if (!empty($inserts)) {
DB::table('todos')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}


return back();
}

}


The line not suppported by version 3.0 is this



Excel::load($path,function($reader) use (&$inserts)









share|improve this question

























  • A File encapsulates the data. developer.mozilla.org/en-US/docs/Web/API/File

    – Roy J
    Nov 26 '18 at 14:27











  • what exactly are you trying to achieve and what is the error you are having ?

    – Mazino S Ukah
    Nov 26 '18 at 14:35











  • @MazinoSUkah, I am trying to submit my form data object with the this.$store.dispatch('uploadTodos', formData);, however my vuex method uploadTodos contains no data. Please view updated question for vuex method

    – TJ Weems
    Nov 26 '18 at 14:38











  • @RoyJ, when I console.log(pair) it shows the contents of the formData object however once it reaches my vuex method it seems to be empty....

    – TJ Weems
    Nov 26 '18 at 14:40














1












1








1


0






So I had asked a question previously, and got a little bit of help as far as logging the results however my results are not making sense.



So I have a input



<input type="file" name="import_file" v-on:change="selectedFile($event)">


The v-on:change binds the selected file to my data object this.file



selectedFile(event) {
this.file = event.target.files[0]
},


and then I submit the file with this method



uploadTodos() {
let formData = new FormData();
formData.append('file', this.file);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
this.$store.dispatch('uploadTodos', formData);
}


However when I submit it seems there is no data attached to formData because my logged result is this



file, [object File]


shouldn't I have my actual data appended to the formData object??



I have referenced other articles on how to post but I am not getting the desired results.



article 1
article2



uploadTodos(context, file) {
console.log(file)
axios.post('/import', file,{ headers: {
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log(response.data)
context.commit('importTodos', response.data)
})
.catch(error => {
console.log(error.response.data)
})
}


when I console.log(file) the formData object is empty



Backend Question
So my issue with Laravel on the backend is with the maatwebsite package. From what I have seen is the 3.0 version does not yet support imports. And the only work around suggested is to install version 2.0? Is this still the only workaround? Here is the controller method



public function importExcel(Request $request) 
{

if (empty($request->file('file')->getRealPath())) {
return back()->with('success','No file selected');
}
else {
$path = $request->file('file')->getRealPath();
$inserts = ;
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts = ['user_id' => $row['user_id'], 'todo' => $row['todo']];
};
}
});

if (!empty($inserts)) {
DB::table('todos')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}


return back();
}

}


The line not suppported by version 3.0 is this



Excel::load($path,function($reader) use (&$inserts)









share|improve this question
















So I had asked a question previously, and got a little bit of help as far as logging the results however my results are not making sense.



So I have a input



<input type="file" name="import_file" v-on:change="selectedFile($event)">


The v-on:change binds the selected file to my data object this.file



selectedFile(event) {
this.file = event.target.files[0]
},


and then I submit the file with this method



uploadTodos() {
let formData = new FormData();
formData.append('file', this.file);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
this.$store.dispatch('uploadTodos', formData);
}


However when I submit it seems there is no data attached to formData because my logged result is this



file, [object File]


shouldn't I have my actual data appended to the formData object??



I have referenced other articles on how to post but I am not getting the desired results.



article 1
article2



uploadTodos(context, file) {
console.log(file)
axios.post('/import', file,{ headers: {
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log(response.data)
context.commit('importTodos', response.data)
})
.catch(error => {
console.log(error.response.data)
})
}


when I console.log(file) the formData object is empty



Backend Question
So my issue with Laravel on the backend is with the maatwebsite package. From what I have seen is the 3.0 version does not yet support imports. And the only work around suggested is to install version 2.0? Is this still the only workaround? Here is the controller method



public function importExcel(Request $request) 
{

if (empty($request->file('file')->getRealPath())) {
return back()->with('success','No file selected');
}
else {
$path = $request->file('file')->getRealPath();
$inserts = ;
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts = ['user_id' => $row['user_id'], 'todo' => $row['todo']];
};
}
});

if (!empty($inserts)) {
DB::table('todos')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}


return back();
}

}


The line not suppported by version 3.0 is this



Excel::load($path,function($reader) use (&$inserts)






vue.js file-upload axios form-data






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 15:31







TJ Weems

















asked Nov 26 '18 at 14:16









TJ WeemsTJ Weems

147110




147110













  • A File encapsulates the data. developer.mozilla.org/en-US/docs/Web/API/File

    – Roy J
    Nov 26 '18 at 14:27











  • what exactly are you trying to achieve and what is the error you are having ?

    – Mazino S Ukah
    Nov 26 '18 at 14:35











  • @MazinoSUkah, I am trying to submit my form data object with the this.$store.dispatch('uploadTodos', formData);, however my vuex method uploadTodos contains no data. Please view updated question for vuex method

    – TJ Weems
    Nov 26 '18 at 14:38











  • @RoyJ, when I console.log(pair) it shows the contents of the formData object however once it reaches my vuex method it seems to be empty....

    – TJ Weems
    Nov 26 '18 at 14:40



















  • A File encapsulates the data. developer.mozilla.org/en-US/docs/Web/API/File

    – Roy J
    Nov 26 '18 at 14:27











  • what exactly are you trying to achieve and what is the error you are having ?

    – Mazino S Ukah
    Nov 26 '18 at 14:35











  • @MazinoSUkah, I am trying to submit my form data object with the this.$store.dispatch('uploadTodos', formData);, however my vuex method uploadTodos contains no data. Please view updated question for vuex method

    – TJ Weems
    Nov 26 '18 at 14:38











  • @RoyJ, when I console.log(pair) it shows the contents of the formData object however once it reaches my vuex method it seems to be empty....

    – TJ Weems
    Nov 26 '18 at 14:40

















A File encapsulates the data. developer.mozilla.org/en-US/docs/Web/API/File

– Roy J
Nov 26 '18 at 14:27





A File encapsulates the data. developer.mozilla.org/en-US/docs/Web/API/File

– Roy J
Nov 26 '18 at 14:27













what exactly are you trying to achieve and what is the error you are having ?

– Mazino S Ukah
Nov 26 '18 at 14:35





what exactly are you trying to achieve and what is the error you are having ?

– Mazino S Ukah
Nov 26 '18 at 14:35













@MazinoSUkah, I am trying to submit my form data object with the this.$store.dispatch('uploadTodos', formData);, however my vuex method uploadTodos contains no data. Please view updated question for vuex method

– TJ Weems
Nov 26 '18 at 14:38





@MazinoSUkah, I am trying to submit my form data object with the this.$store.dispatch('uploadTodos', formData);, however my vuex method uploadTodos contains no data. Please view updated question for vuex method

– TJ Weems
Nov 26 '18 at 14:38













@RoyJ, when I console.log(pair) it shows the contents of the formData object however once it reaches my vuex method it seems to be empty....

– TJ Weems
Nov 26 '18 at 14:40





@RoyJ, when I console.log(pair) it shows the contents of the formData object however once it reaches my vuex method it seems to be empty....

– TJ Weems
Nov 26 '18 at 14:40












2 Answers
2






active

oldest

votes


















1














I have reproduced your code and it seems to be working fine




when I console.log(file) the formData object is empty




Yeah the output should be an empty object when you console, that's the way javascript works.



after casting the output to an array i get the output in the image below:



enter image description here






const store = new Vuex.Store({
actions: {
uploadTodos(context, file) {
console.log([...file])
axios.post('/import', file,{ headers: {
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log(response.data)
context.commit('importTodos', response.data)
})
.catch(error => {
console.log(error.response.data)
})
}
}
})

const app = new Vue({
store,
data: {
file: null
},
methods: {
selectedFile(event) {
console.log(event);
this.file = event.target.files[0]
},
uploadTodos() {
let formData = new FormData();
formData.append('file', this.file);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
this.$store.dispatch('uploadTodos', formData);
}
},
el: '#app'
})

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<input type="file" name="import_file" @change="selectedFile($event)">
<button @click="uploadTodos">
Submit
</button>
</div>








share|improve this answer
























  • yes I am now getting the same results. I guess I am having an issue with the data being received on the back end. I appreciate the help!

    – TJ Weems
    Nov 26 '18 at 15:04











  • you are welcome..what language/framework are you using on the backend ?

    – Mazino S Ukah
    Nov 26 '18 at 15:05











  • Laravel 5.6. I added the maatwebsite package, so I can upload excel files, however when I reach my controller method I am doing something wrong. any experience with it?

    – TJ Weems
    Nov 26 '18 at 15:07











  • I have experience with laravel... Can you update your question showing what you have tried for the laravel backend?

    – Mazino S Ukah
    Nov 26 '18 at 15:10






  • 1





    please see my answer post for the maatwebsit/excel issue. It turns out it does support imports.

    – TJ Weems
    Nov 26 '18 at 18:13



















1














This post answers the second part of the question. At first from what I read maatwebsite/excel version 3.0 does not support import. However I am using version 3.1.0 which does support imports. However the method for importing still does not suppport Excel::load(). You should instead use Excel::import() and follow the given rules for passing in parameters. Which of course can be modified to suit your needs. But anyways here is a simple example of how I am using it for anyone interested.



First create import file for whatever model it is. For me it is Todos.



<?php

namespace AppImports;

use AppTodo;

use MaatwebsiteExcelConcernsToModel;

class TodoImport implements ToModel
{
/**
* @param array $row
*
* @return IlluminateDatabaseEloquentModel|null
*/
public function model(array $row)
{
return new Todo([
'user_id' => $row[0],
'todo' => $row[1],
]);
}
}


next you have your controller handling the file, and passing it to the todosimport file



 public function importExcel(Request $request) 
{

if (empty($request->file('file')->getRealPath())) {
return back()->with('success','No file selected');
}
else {
Excel::import(new TodoImport, $request->file('file'));

return response('Import Succesful, Please Refresh Page');
}

}


notice the Excel::import(). I pass in the new Todo model and the file received.



of course for me since I am doing it by ajax I use this route to ping the method



Route::post('/import', 'TodosController@importExcel');





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53483025%2fhow-to-use-formdata-for-uploading-file-in-vue%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I have reproduced your code and it seems to be working fine




    when I console.log(file) the formData object is empty




    Yeah the output should be an empty object when you console, that's the way javascript works.



    after casting the output to an array i get the output in the image below:



    enter image description here






    const store = new Vuex.Store({
    actions: {
    uploadTodos(context, file) {
    console.log([...file])
    axios.post('/import', file,{ headers: {
    'Content-Type': 'multipart/form-data'
    }})
    .then(response => {
    console.log(response.data)
    context.commit('importTodos', response.data)
    })
    .catch(error => {
    console.log(error.response.data)
    })
    }
    }
    })

    const app = new Vue({
    store,
    data: {
    file: null
    },
    methods: {
    selectedFile(event) {
    console.log(event);
    this.file = event.target.files[0]
    },
    uploadTodos() {
    let formData = new FormData();
    formData.append('file', this.file);
    for(var pair of formData.entries()) {
    console.log(pair[0]+ ', '+ pair[1]);
    }
    this.$store.dispatch('uploadTodos', formData);
    }
    },
    el: '#app'
    })

    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/vuex"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <div id="app">
    <input type="file" name="import_file" @change="selectedFile($event)">
    <button @click="uploadTodos">
    Submit
    </button>
    </div>








    share|improve this answer
























    • yes I am now getting the same results. I guess I am having an issue with the data being received on the back end. I appreciate the help!

      – TJ Weems
      Nov 26 '18 at 15:04











    • you are welcome..what language/framework are you using on the backend ?

      – Mazino S Ukah
      Nov 26 '18 at 15:05











    • Laravel 5.6. I added the maatwebsite package, so I can upload excel files, however when I reach my controller method I am doing something wrong. any experience with it?

      – TJ Weems
      Nov 26 '18 at 15:07











    • I have experience with laravel... Can you update your question showing what you have tried for the laravel backend?

      – Mazino S Ukah
      Nov 26 '18 at 15:10






    • 1





      please see my answer post for the maatwebsit/excel issue. It turns out it does support imports.

      – TJ Weems
      Nov 26 '18 at 18:13
















    1














    I have reproduced your code and it seems to be working fine




    when I console.log(file) the formData object is empty




    Yeah the output should be an empty object when you console, that's the way javascript works.



    after casting the output to an array i get the output in the image below:



    enter image description here






    const store = new Vuex.Store({
    actions: {
    uploadTodos(context, file) {
    console.log([...file])
    axios.post('/import', file,{ headers: {
    'Content-Type': 'multipart/form-data'
    }})
    .then(response => {
    console.log(response.data)
    context.commit('importTodos', response.data)
    })
    .catch(error => {
    console.log(error.response.data)
    })
    }
    }
    })

    const app = new Vue({
    store,
    data: {
    file: null
    },
    methods: {
    selectedFile(event) {
    console.log(event);
    this.file = event.target.files[0]
    },
    uploadTodos() {
    let formData = new FormData();
    formData.append('file', this.file);
    for(var pair of formData.entries()) {
    console.log(pair[0]+ ', '+ pair[1]);
    }
    this.$store.dispatch('uploadTodos', formData);
    }
    },
    el: '#app'
    })

    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/vuex"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <div id="app">
    <input type="file" name="import_file" @change="selectedFile($event)">
    <button @click="uploadTodos">
    Submit
    </button>
    </div>








    share|improve this answer
























    • yes I am now getting the same results. I guess I am having an issue with the data being received on the back end. I appreciate the help!

      – TJ Weems
      Nov 26 '18 at 15:04











    • you are welcome..what language/framework are you using on the backend ?

      – Mazino S Ukah
      Nov 26 '18 at 15:05











    • Laravel 5.6. I added the maatwebsite package, so I can upload excel files, however when I reach my controller method I am doing something wrong. any experience with it?

      – TJ Weems
      Nov 26 '18 at 15:07











    • I have experience with laravel... Can you update your question showing what you have tried for the laravel backend?

      – Mazino S Ukah
      Nov 26 '18 at 15:10






    • 1





      please see my answer post for the maatwebsit/excel issue. It turns out it does support imports.

      – TJ Weems
      Nov 26 '18 at 18:13














    1












    1








    1







    I have reproduced your code and it seems to be working fine




    when I console.log(file) the formData object is empty




    Yeah the output should be an empty object when you console, that's the way javascript works.



    after casting the output to an array i get the output in the image below:



    enter image description here






    const store = new Vuex.Store({
    actions: {
    uploadTodos(context, file) {
    console.log([...file])
    axios.post('/import', file,{ headers: {
    'Content-Type': 'multipart/form-data'
    }})
    .then(response => {
    console.log(response.data)
    context.commit('importTodos', response.data)
    })
    .catch(error => {
    console.log(error.response.data)
    })
    }
    }
    })

    const app = new Vue({
    store,
    data: {
    file: null
    },
    methods: {
    selectedFile(event) {
    console.log(event);
    this.file = event.target.files[0]
    },
    uploadTodos() {
    let formData = new FormData();
    formData.append('file', this.file);
    for(var pair of formData.entries()) {
    console.log(pair[0]+ ', '+ pair[1]);
    }
    this.$store.dispatch('uploadTodos', formData);
    }
    },
    el: '#app'
    })

    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/vuex"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <div id="app">
    <input type="file" name="import_file" @change="selectedFile($event)">
    <button @click="uploadTodos">
    Submit
    </button>
    </div>








    share|improve this answer













    I have reproduced your code and it seems to be working fine




    when I console.log(file) the formData object is empty




    Yeah the output should be an empty object when you console, that's the way javascript works.



    after casting the output to an array i get the output in the image below:



    enter image description here






    const store = new Vuex.Store({
    actions: {
    uploadTodos(context, file) {
    console.log([...file])
    axios.post('/import', file,{ headers: {
    'Content-Type': 'multipart/form-data'
    }})
    .then(response => {
    console.log(response.data)
    context.commit('importTodos', response.data)
    })
    .catch(error => {
    console.log(error.response.data)
    })
    }
    }
    })

    const app = new Vue({
    store,
    data: {
    file: null
    },
    methods: {
    selectedFile(event) {
    console.log(event);
    this.file = event.target.files[0]
    },
    uploadTodos() {
    let formData = new FormData();
    formData.append('file', this.file);
    for(var pair of formData.entries()) {
    console.log(pair[0]+ ', '+ pair[1]);
    }
    this.$store.dispatch('uploadTodos', formData);
    }
    },
    el: '#app'
    })

    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/vuex"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <div id="app">
    <input type="file" name="import_file" @change="selectedFile($event)">
    <button @click="uploadTodos">
    Submit
    </button>
    </div>








    const store = new Vuex.Store({
    actions: {
    uploadTodos(context, file) {
    console.log([...file])
    axios.post('/import', file,{ headers: {
    'Content-Type': 'multipart/form-data'
    }})
    .then(response => {
    console.log(response.data)
    context.commit('importTodos', response.data)
    })
    .catch(error => {
    console.log(error.response.data)
    })
    }
    }
    })

    const app = new Vue({
    store,
    data: {
    file: null
    },
    methods: {
    selectedFile(event) {
    console.log(event);
    this.file = event.target.files[0]
    },
    uploadTodos() {
    let formData = new FormData();
    formData.append('file', this.file);
    for(var pair of formData.entries()) {
    console.log(pair[0]+ ', '+ pair[1]);
    }
    this.$store.dispatch('uploadTodos', formData);
    }
    },
    el: '#app'
    })

    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/vuex"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <div id="app">
    <input type="file" name="import_file" @change="selectedFile($event)">
    <button @click="uploadTodos">
    Submit
    </button>
    </div>





    const store = new Vuex.Store({
    actions: {
    uploadTodos(context, file) {
    console.log([...file])
    axios.post('/import', file,{ headers: {
    'Content-Type': 'multipart/form-data'
    }})
    .then(response => {
    console.log(response.data)
    context.commit('importTodos', response.data)
    })
    .catch(error => {
    console.log(error.response.data)
    })
    }
    }
    })

    const app = new Vue({
    store,
    data: {
    file: null
    },
    methods: {
    selectedFile(event) {
    console.log(event);
    this.file = event.target.files[0]
    },
    uploadTodos() {
    let formData = new FormData();
    formData.append('file', this.file);
    for(var pair of formData.entries()) {
    console.log(pair[0]+ ', '+ pair[1]);
    }
    this.$store.dispatch('uploadTodos', formData);
    }
    },
    el: '#app'
    })

    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/vuex"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <div id="app">
    <input type="file" name="import_file" @change="selectedFile($event)">
    <button @click="uploadTodos">
    Submit
    </button>
    </div>






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 26 '18 at 15:00









    Mazino S UkahMazino S Ukah

    8111926




    8111926













    • yes I am now getting the same results. I guess I am having an issue with the data being received on the back end. I appreciate the help!

      – TJ Weems
      Nov 26 '18 at 15:04











    • you are welcome..what language/framework are you using on the backend ?

      – Mazino S Ukah
      Nov 26 '18 at 15:05











    • Laravel 5.6. I added the maatwebsite package, so I can upload excel files, however when I reach my controller method I am doing something wrong. any experience with it?

      – TJ Weems
      Nov 26 '18 at 15:07











    • I have experience with laravel... Can you update your question showing what you have tried for the laravel backend?

      – Mazino S Ukah
      Nov 26 '18 at 15:10






    • 1





      please see my answer post for the maatwebsit/excel issue. It turns out it does support imports.

      – TJ Weems
      Nov 26 '18 at 18:13



















    • yes I am now getting the same results. I guess I am having an issue with the data being received on the back end. I appreciate the help!

      – TJ Weems
      Nov 26 '18 at 15:04











    • you are welcome..what language/framework are you using on the backend ?

      – Mazino S Ukah
      Nov 26 '18 at 15:05











    • Laravel 5.6. I added the maatwebsite package, so I can upload excel files, however when I reach my controller method I am doing something wrong. any experience with it?

      – TJ Weems
      Nov 26 '18 at 15:07











    • I have experience with laravel... Can you update your question showing what you have tried for the laravel backend?

      – Mazino S Ukah
      Nov 26 '18 at 15:10






    • 1





      please see my answer post for the maatwebsit/excel issue. It turns out it does support imports.

      – TJ Weems
      Nov 26 '18 at 18:13

















    yes I am now getting the same results. I guess I am having an issue with the data being received on the back end. I appreciate the help!

    – TJ Weems
    Nov 26 '18 at 15:04





    yes I am now getting the same results. I guess I am having an issue with the data being received on the back end. I appreciate the help!

    – TJ Weems
    Nov 26 '18 at 15:04













    you are welcome..what language/framework are you using on the backend ?

    – Mazino S Ukah
    Nov 26 '18 at 15:05





    you are welcome..what language/framework are you using on the backend ?

    – Mazino S Ukah
    Nov 26 '18 at 15:05













    Laravel 5.6. I added the maatwebsite package, so I can upload excel files, however when I reach my controller method I am doing something wrong. any experience with it?

    – TJ Weems
    Nov 26 '18 at 15:07





    Laravel 5.6. I added the maatwebsite package, so I can upload excel files, however when I reach my controller method I am doing something wrong. any experience with it?

    – TJ Weems
    Nov 26 '18 at 15:07













    I have experience with laravel... Can you update your question showing what you have tried for the laravel backend?

    – Mazino S Ukah
    Nov 26 '18 at 15:10





    I have experience with laravel... Can you update your question showing what you have tried for the laravel backend?

    – Mazino S Ukah
    Nov 26 '18 at 15:10




    1




    1





    please see my answer post for the maatwebsit/excel issue. It turns out it does support imports.

    – TJ Weems
    Nov 26 '18 at 18:13





    please see my answer post for the maatwebsit/excel issue. It turns out it does support imports.

    – TJ Weems
    Nov 26 '18 at 18:13













    1














    This post answers the second part of the question. At first from what I read maatwebsite/excel version 3.0 does not support import. However I am using version 3.1.0 which does support imports. However the method for importing still does not suppport Excel::load(). You should instead use Excel::import() and follow the given rules for passing in parameters. Which of course can be modified to suit your needs. But anyways here is a simple example of how I am using it for anyone interested.



    First create import file for whatever model it is. For me it is Todos.



    <?php

    namespace AppImports;

    use AppTodo;

    use MaatwebsiteExcelConcernsToModel;

    class TodoImport implements ToModel
    {
    /**
    * @param array $row
    *
    * @return IlluminateDatabaseEloquentModel|null
    */
    public function model(array $row)
    {
    return new Todo([
    'user_id' => $row[0],
    'todo' => $row[1],
    ]);
    }
    }


    next you have your controller handling the file, and passing it to the todosimport file



     public function importExcel(Request $request) 
    {

    if (empty($request->file('file')->getRealPath())) {
    return back()->with('success','No file selected');
    }
    else {
    Excel::import(new TodoImport, $request->file('file'));

    return response('Import Succesful, Please Refresh Page');
    }

    }


    notice the Excel::import(). I pass in the new Todo model and the file received.



    of course for me since I am doing it by ajax I use this route to ping the method



    Route::post('/import', 'TodosController@importExcel');





    share|improve this answer




























      1














      This post answers the second part of the question. At first from what I read maatwebsite/excel version 3.0 does not support import. However I am using version 3.1.0 which does support imports. However the method for importing still does not suppport Excel::load(). You should instead use Excel::import() and follow the given rules for passing in parameters. Which of course can be modified to suit your needs. But anyways here is a simple example of how I am using it for anyone interested.



      First create import file for whatever model it is. For me it is Todos.



      <?php

      namespace AppImports;

      use AppTodo;

      use MaatwebsiteExcelConcernsToModel;

      class TodoImport implements ToModel
      {
      /**
      * @param array $row
      *
      * @return IlluminateDatabaseEloquentModel|null
      */
      public function model(array $row)
      {
      return new Todo([
      'user_id' => $row[0],
      'todo' => $row[1],
      ]);
      }
      }


      next you have your controller handling the file, and passing it to the todosimport file



       public function importExcel(Request $request) 
      {

      if (empty($request->file('file')->getRealPath())) {
      return back()->with('success','No file selected');
      }
      else {
      Excel::import(new TodoImport, $request->file('file'));

      return response('Import Succesful, Please Refresh Page');
      }

      }


      notice the Excel::import(). I pass in the new Todo model and the file received.



      of course for me since I am doing it by ajax I use this route to ping the method



      Route::post('/import', 'TodosController@importExcel');





      share|improve this answer


























        1












        1








        1







        This post answers the second part of the question. At first from what I read maatwebsite/excel version 3.0 does not support import. However I am using version 3.1.0 which does support imports. However the method for importing still does not suppport Excel::load(). You should instead use Excel::import() and follow the given rules for passing in parameters. Which of course can be modified to suit your needs. But anyways here is a simple example of how I am using it for anyone interested.



        First create import file for whatever model it is. For me it is Todos.



        <?php

        namespace AppImports;

        use AppTodo;

        use MaatwebsiteExcelConcernsToModel;

        class TodoImport implements ToModel
        {
        /**
        * @param array $row
        *
        * @return IlluminateDatabaseEloquentModel|null
        */
        public function model(array $row)
        {
        return new Todo([
        'user_id' => $row[0],
        'todo' => $row[1],
        ]);
        }
        }


        next you have your controller handling the file, and passing it to the todosimport file



         public function importExcel(Request $request) 
        {

        if (empty($request->file('file')->getRealPath())) {
        return back()->with('success','No file selected');
        }
        else {
        Excel::import(new TodoImport, $request->file('file'));

        return response('Import Succesful, Please Refresh Page');
        }

        }


        notice the Excel::import(). I pass in the new Todo model and the file received.



        of course for me since I am doing it by ajax I use this route to ping the method



        Route::post('/import', 'TodosController@importExcel');





        share|improve this answer













        This post answers the second part of the question. At first from what I read maatwebsite/excel version 3.0 does not support import. However I am using version 3.1.0 which does support imports. However the method for importing still does not suppport Excel::load(). You should instead use Excel::import() and follow the given rules for passing in parameters. Which of course can be modified to suit your needs. But anyways here is a simple example of how I am using it for anyone interested.



        First create import file for whatever model it is. For me it is Todos.



        <?php

        namespace AppImports;

        use AppTodo;

        use MaatwebsiteExcelConcernsToModel;

        class TodoImport implements ToModel
        {
        /**
        * @param array $row
        *
        * @return IlluminateDatabaseEloquentModel|null
        */
        public function model(array $row)
        {
        return new Todo([
        'user_id' => $row[0],
        'todo' => $row[1],
        ]);
        }
        }


        next you have your controller handling the file, and passing it to the todosimport file



         public function importExcel(Request $request) 
        {

        if (empty($request->file('file')->getRealPath())) {
        return back()->with('success','No file selected');
        }
        else {
        Excel::import(new TodoImport, $request->file('file'));

        return response('Import Succesful, Please Refresh Page');
        }

        }


        notice the Excel::import(). I pass in the new Todo model and the file received.



        of course for me since I am doing it by ajax I use this route to ping the method



        Route::post('/import', 'TodosController@importExcel');






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 '18 at 18:12









        TJ WeemsTJ Weems

        147110




        147110






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53483025%2fhow-to-use-formdata-for-uploading-file-in-vue%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks