SoFunction
Updated on 2025-02-28

Vue formData implements image upload

This article shares the specific code for Vue formData to upload images for your reference. The specific content is as follows

import Vue from 'vue'
 
/**
  * Image upload
  * All Vue instances have been injected,
  * Call $uploadFile(id) in the template template
  * Call this.$uploadFile(id) in the component method
  */
const uploadFile = (id) => {
 let promise = new Promise((resolve, reject) => {
  let file = null
  let el = null
  let i = 0
  let formData = new FormData()
  (id).click()
  el = (id)
  ('change', function (e) {
   i++
   if (i !== 1) {
    return false
   } else {
    file = [0]
    ('file', file)
    ('fileType', 'IMAGE')
    // Data request    (, formData).then(res => {
     // Return to the image url     resolve(res)
    }).catch(err => {
     reject(err)
    })
   }
  })
 })
 return promise
}
 
.$uploadFile = uploadFile

axios request header settings

import Vue from 'vue'
import { baseURL } from '@/config/env'
import axios from 'axios'
 
// formdata requestconst axiosT = ({
 baseURL: baseURL,
 headers: {
  'Content-Type': 'multipart/form-data'
 }
})
 
const XHR = ({method = 'post', qs = true, loading = false, loginRequire = true, reqComplex = false, reqContentType = 'urlencoded'}) => {
 // Method of success with request progress bar const sucFunX = res => {
  return 
 }
 // Successful execution method const sucFunC = res => {
  return 
 }
 // Method of failure with request progress bar const errFunX = err => {
  (err, ())
 }
 // Failed to perform the access const errFunC = err => {
  (err)
 }
 // Determine whether Longing is needed const sucFun = loading ? sucFunX : sucFunC
 // Determine whether Longing is needed const errFun = loading ? errFunX : errFunC
 return {user, sucFun, errFun}
}
 
// Form request Image uploadconst axiosfrom = function (url = '', data = {}) {
 let {sucFun, errFun} = XHR({loading: false})
 return (url, data).then(sucFun).catch(errFun)
}
// Form Request.$axiosfrom = axiosfrom
 = axiosfrom

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.