实现上传图片
<n-form-item path="path" label="相关文档">
<n-upload
multiple
directory-dnd
action="http:xxxx地址"
:headers="{
Authorization: `Bearer ${token}`,
}"
@change="handlecjamge"
@remove="handleRemove"
v-model:file-list="fileList"
:custom-request="customAddUploadRequest"
:max="1"
>
<n-upload-dragger>
引入组件api
import { lyla } from 'lyla';
import type { useDialog, UploadCustomRequestOptions } from 'naive-ui';
import { storage } from '@/utils/Storage';
import { ACCESS_TOKEN } from '@/store/mutation-types';
let token = ref<string>('');
token.value = storage.get(ACCESS_TOKEN);
实现代码
const fileList = ref([]);
fileList.value = [];
fileList.value.push({
id: 1,
url: 'http://10.3.10.37:9000' + editData.value.filePath,
name: editData.value.fileName,
status: 'finished',
});
事件
const customAddUploadRequest = ({
file,
data,
headers,
withCredentials,
action,
onFinish,
onError,
onProgress,
}: UploadCustomRequestOptions) => {
const formData = new FormData();
if (data) {
Object.keys(data).forEach((key) => {
formData.append(key, data[key as keyof UploadCustomRequestOptions['data']]);
});
}
formData.append('files', file.file as File);
lyla
.post(action as string, {
withCredentials,
headers: headers as Record<string, string>,
body: formData,
onUploadProgress: ({ percent }) => {
onProgress({ percent: Math.ceil(percent) });
},
})
.then(({ json }) => {
let jsonnn = JSON.parse(JSON.stringify(json));
console.log(jsonnn, 'jsonnn');
filePath.value = jsonnn.data[0].filePath;
fileName.value = jsonnn.data[0].name;
editData.value.filePath = filePath.value;
editData.value.fileName = fileName.value;
console.log(filePath.value, ' filePath.value');
})
.catch((error) => {
console.log(error.message);
// onError();
});
};