html
<input type="file" id="fileUploadEle" ref="fileUploadEle" style="display:none;" accept=".png, .jpg" @change="selectFile" /> <label for="fileUploadEle"> <el-button type="primary" @click="openFileDialog">上传头像</el-button> </label>
js
let fileUploadEle = ref<object>({});
let upFile: any = null;
function openFileDialog() { // document.getElementById('fileUploadEle').click(); (fileUploadEle.value as HTMLElement).click(); } function selectFile(e: any) { let file = e.target.files[0]; upFile = file; } //上传2,点击按钮上传。 const uploadFiles = async () => { await uploadFilesReq(upFile).then((res) => { console.log(res); if (res.status == 200 && res.data.errorCode == '0') { // ElMessage({ showClose: true, message: "操作成功", grouping: true, type: 'success' }); form.sysUserAvatar = res.data.data[0]; } else { ElMessage({ showClose: true, message: "图片上传失败:" + res.data.message, grouping: true, type: 'error' }); } }).catch(err => { ElMessage({ showClose: true, message: "图片上传错误:" + JSON.stringify(err), grouping: true, type: 'error' }); }); }
common
import { getCookie } from '@/common/cookie'
import Axios from "axios"
// import pinia from '@/stores/store'
// import { useSystemDataStore } from '@/stores/index'
// SystemDataStore 可以在本文件中随意使用
// const SystemDataStore = useSystemDataStore(pinia);
let domainUrl = import.meta.env.VITE_ApiDomain;
//上传2,点击按钮上传。
export async function uploadFilesReq(upFile: any) {
/* eslint-disable no-undef */
let param = new FormData(); // 创建form对象
param.append("file", upFile); // 通过append向form对象添加数据
// console.log(param.get("file")); // FormData私有类对象,访问不到,可以通过get判断值是否传进去
let config = {
headers: { "Content-Type": "multipart/form-data","Authorization": "","Access-Control-Allow-Origin-Type":"*"},
};
let token = getCookie('XSRF-TOKEN');
if (token != undefined && token != '' && token != null) {
// let each request carry token
// ['X-Token'] is a custom headers key
// please modify it according to the actual situation
config.headers['Authorization'] = 'Bearer ' + token;
}
// 添加请求头 domainUrl
return await Axios.post(domainUrl + "Upload/UploadFiles", param, config);
// return await Axios.post(SystemDataStore.apiDomain + "Upload/UploadFiles", param, config);
}
浙公网安备 33010602011771号