使用 FormData 对象 FormData是一个用于创建表单数据的 API,可用于发送包含文件和其他表单数据的multipart/form-data请求。这是处理文件上传的常用方法。通过FormData对象,可以将文件数据添加到表单中,然后使用 Axios 的post或put方法发送请求
在. env. development 文件中配置地址
# 只在开发模式中被载入
VITE_PORT = 8001 # 网站根目录
VITE_PUBLIC_PATH = / # 是否开启mock
VITE_USE_MOCK = false # 网站前缀
VITE_BASE_URL = / # 是否删除console
VITE_DROP_CONSOLE = false # 跨域代理,可以配置多个,请注意不要换行
#VITE_PROXY = [ [ "/appApi" , "http://localhost:8001" ] , [ "/upload" , "http://localhost:8001/upload" ] ]
#VITE_PROXY = [ [ "/api" , "https://naive-ui-admin" ] ] # API 接口地址
VITE_GLOB_API_URL = http: / / 247.94 .82 .23 : 8091 # 图片上传地址
VITE_GLOB_UPLOAD_URL = http: / / 247.94 .82 .23 : 8091 / file/ upload/ # 图片前缀地址
VITE_GLOB_IMG_URL = # 接口前缀
VITE_GLOB_API_URL_PREFIX = / const filePath = import . meta. env. VITE_GLOB_API_URL ; export function uploadfile ( file ) { console. log ( file) ; console. log ( filePath+ '/upload/file' ) ; const formData = new FormData ( ) ; formData. append ( 'file' , file) ; return new Promise ( function ( resolve ) { axios. post ( filePath+ '/upload/file' , formData, { headers : { 'Content-Type' : 'multipart/form-data' } } ) . then ( response => { console. log ( '上传成功' , response. data) ; resolve ( response. data) } ) . catch ( error => { console. error ( '上传失败' , error) ; resolve ( error) } ) ; } ) } import * as jk from '@/api/appw' ;
const afterRead = async ( file ) => { console. log ( file) ; let dat = jk. uploadfile ( file. file) ; console. log ( dat) ; }
const axios = require ( 'axios' ) ;
const fileInput = document. querySelector ( '#fileInput' ) ;
const file = fileInput. files[ 0 ] ;
const formData = new FormData ( ) ;
formData. append ( 'file' , file) ;
axios. post ( '/upload' , formData, { headers : { 'Content-Type' : 'multipart/form-data' }
} ) . then ( response => { console. log ( '上传成功' , response. data) ;
} ) . catch ( error => { console. error ( '上传失败' , error) ;
} ) ;