Advertisement
Guest User

Nuxt.js + Netlify form with input file

a guest
Sep 9th, 2019
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <template>
  2.   <div class="question-form">
  3.     <form name="ask-question"
  4.           method="post"
  5.           data-netlify="true"
  6.           data-netlify-honeypot="bot-field"
  7.           @submit.prevent="handleSubmit"
  8.           enctype="multipart/form-data">
  9.  
  10.     <input type="hidden" name="form-name" value="ask-question" />
  11.  
  12.       <ul>
  13.         <li>
  14.           <label>
  15.             Name:
  16.             <input
  17.               type="text"
  18.               name="name"
  19.               @input="ev => form.name = ev.target.value"
  20.               >
  21.           </label>
  22.         </li>
  23.         <li>
  24.           <label>
  25.             Upload:
  26.             <input
  27.               type="file"
  28.               name="attach"
  29.               ref="file"
  30.               @change="addFile()"
  31.               >
  32.           </label>
  33.         </li>
  34.       </ul>
  35.       <button type="submit" class="submit-button">Send</button>
  36.     </form>
  37.   </div>
  38. </template>
  39.  
  40. <script>
  41. import axios from "axios"
  42.  
  43. export default {
  44.   data() {
  45.     return {
  46.       form: {
  47.         name: "",
  48.         attach: ""
  49.       },
  50.     };
  51.   },
  52.   methods: {
  53.     addFile() {
  54.       this.form.attach = this.$refs.file.files[0];
  55.     },
  56.     encode (data) {
  57.         .map(
  58.           key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
  59.         )
  60.         .join("&"))
  61.       return Object.keys(data)
  62.         .map(
  63.           key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
  64.         )
  65.         .join("&");
  66.     },
  67.     handleSubmit() {
  68.       const data = {
  69.         "form-name": "ask-question",
  70.         "name": this.form.name,
  71.         "attach": this.form.attach
  72.       }
  73.       const axiosConfig = {
  74.         header: { "Content-Type": "multipart/form-data" }
  75.       };
  76.       axios.post(
  77.         "/",
  78.         this.encode({
  79.           data
  80.         }),
  81.         axiosConfig
  82.       )
  83.       .then(function (response) {
  84.           console.log(response);
  85.         })
  86.       .catch(function (error) {
  87.         console.log(error);
  88.       });
  89.     }
  90.   }
  91. };
  92. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement