The need to upload files is often encountered during project development. In this article, we will introduce in detail the use of el-upload in elementplus to upload files.
Let’s first take a look at what properties and events el-upload can configure.
action: Request url
headers: Set the upload request header
method: Set the upload request method
multiple: Whether to support multiple selection of files
data: Additional parameters included when uploading
name: Uploaded file field name
with-credentials: Supports sending cookie credential information
The above parameters are used when requesting in the default way of action. If we use a custom request method, these attributes will basically not be used.
show-file-list: Whether to display the uploaded file list
drag: Whether to enable drag and drop upload
accept: Accept the uploaded file type
on-preview: The hook when clicking the uploaded file in the file list
on-remove: The hook when removing files from the file list
on-success: The hook when the file upload is successful
on-error: Hooks when file upload fails
on-progress: Hooks when file uploads
on-change: Hooks when file status changes, Added, both upload success and failure will be called
on-exceed: hook executed when the limit is exceeded
before-upload: file upload For the previous hook, the parameter is the uploaded file. If false
is returned or Promise
is returned and is rejected, the upload will stop.
before-remove: The hook before deleting the file. The parameters are the uploaded file and the file list. If it returns false
or returns Promise
and If rejected, deletion will stop.
file-list/v-model:file-list: Default file upload
list-type: The type of file list, 'text ' | 'picture' | 'picture-card'.
auto-upload: Whether to automatically upload files
http-request: Override the default Xhr behavior and allow you to implement the request to upload files
disabled: Whether to disable uploading
limit: The maximum number of files allowed to be uploaded
abort: Cancel upload request
submit: Manual upload file list
clearFiles: Cleared List of uploaded files (this method does not support calling in before-upload
)
handleStart: Manually select files
handleRemove: Manually remove files. file
and rawFile
have been merged.
When uploading pictures, we usually rewrite the http request and do not use the default action to request, so we usually set the action to &lsquo ;#’.
<template> <div> <el-upload action="#" :headers="headers" :list-type="listType" :http-request="uploadAction" :on-exceed="handleExceed" :on-remove="handleRemove" :before-upload="beforeUpload" :on-success="uploadSuccess" :on-error="uploadError" :on-progress="uploadProgress" :file-list="fileListCopy.data" ref="upload" :multiple="true" :limit='limit' :disabled="disabled" :data="paramData" > <el-icon><Plus /></el-icon> <template #file="{ file }"> <div> <img :src="file.url" alt="" /> <span class="el-upload-list__item-actions"> <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)" > <el-icon><zoom-in /></el-icon> </span> <span class="el-upload-list__item-delete" @click="handleRemove(file)" > <el-icon><Delete /></el-icon> </span> </span> </div> </template> </el-upload> <el-dialog v-model="previewVisible"> <img w-full :src="dialogImageUrl" alt="Preview Image" /> </el-dialog> </div> </template> <script> export default { name: 'uploadImg' } </script> <script setup> import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'; import { reactive, ref, defineProps, defineEmits, computed, getCurrentInstance } from 'vue'; import { ElMessage } from 'element-plus'; const props = defineProps({ // 允许上传文件件的最大数量 limit:{ type:Number }, // 是否禁用上传 disabled:{ type:Boolean, default:false }, // 文件列表类型 listType:{ type:String, default:'picture-card' }, // 上传时携带的额外参数 paramData: { type:String } }); const emits = defineEmits([]); const cns = getCurrentInstance(); const globObj = cns.appContext.config.globalProperties; const previewVisible = ref(false); const dialogImageUrl = ref(''); const fileListCopy = reactive({ data: [] }); const onece = ref(false); const myChangeFile = ref(''); const changeFileIndex = ref(-1); const uploadImgArr = reactive({ data: [] }); const headers = reactive({}); // 预览大图 const handlePictureCardPreview = (uploadFile) => { dialogImageUrl.value = uploadFile.url; previewVisible.value = true; }; // 移除图片 const handleRemove = (file, fileList) => { console.log('handleRemove', handleRemove); console.log('file', file); console.log('fileList', fileList); fileListCopy.data = fileListCopy.data.filter(v => v.uid !== file.uid); }; // 文件上传数量限制 const handleExceed = (files, fileList) => { if (props.limit) { ElMessage.error(`只能上传${props.limit}张图片`); } console.log('handleExceed', handleExceed); console.log('files', files); console.log('fileList', fileList); }; // 上传请求 const uploadAction = (option) => { let formData = new FormData(); const url = ''; globObj.$axios({ url: url, method: 'post', transformRequest: [function(data, headers) { // 去除post请求默认的Content-Type delete headers['Content-Type'] return data }], data: formData, timeout: 300000 }).then(res => { ElMessage.success('资产添加成功'); }).catch((err) => { console.log(err); }); } // 格式大小的限制 const beforeUpload = (file) => { let isJPG = false, fileType = file.type.split('/')[0]; if(file.type === "image/jpeg" || file.type === "image/png") { isJPG = true; } else { isJPG = false; } const isLt2M = file.size / 1024 / 1024; if (fileType != 'image' || isLt2M > 2) { ElMessage.error("请上传2M以内的图片文件!"); return false } return true; }; // 文件上传成功时的钩子 const uploadSuccess = (response, file, fileList) => { // 上传成功之后后台返回的数据 console.log('uploadSuccess', uploadSuccess); }; const uploadProgress = (e, file, fileList) => { console.log('uploadProgress', uploadProgress) }; const uploadError = (err, file, fileList) => { console.log('uploadError', uploadError); }; </script>
Generally, when uploading a file, the Content-Type in the request header: multipart/form-data; in our requirements, we also need to set the random number of the file, so the request header needs to This is Content-Type: multipart/form-data; boundary=----WebKitFormBoundarypzSlbADtTRuFx5FC.
The following is the problem I encountered.
Content-Type: multipart/form-data is set; at this time, the request has no random number boundary=----WebKitFormBoundarypzSlbADtTRuFx5FC.
If you set the global content-type, you will find that the upload interface setting multipart/form-data does not work. Because there is no Boundary, the upload must fail with server 500.
Then I tried to add Boundary manually, but this time the error changed to 400
After querying the information, it was said that there is no need to set Content-Type: multipart/form-data; As long as the parameter is in the formData form, the browser will automatically convert the Content-Type of the request header into Content-Type: multipart/form-data; boundary=----WebKitFormBoundarypzSlbADtTRuFx5FC.
But if I don’t set it, it will be the default application/json.
So I checked the information and found that the transformRequest attribute of axios can modify the request data before sending the request data to the server. Because our request is in the default post request method, the value of Content-Type is application/json, and the default needs to be removed. value so that the browser can automatically add it.
globObj.$axios({ url: url, method: 'post', transformRequest: [function(data, headers) { // 去除post请求默认的Content-Type delete headers['Content-Type'] return data }], data: formData, timeout: 300000 }).then(res => { ElMessage.success('资产添加成功'); }).catch((err) => { console.log(err); });
If you want to pass other parameters, the other parameters must also be appended, otherwise parameter errors may be reported.
const formData = new FormData(); formData.append('file', file); // 其他参数 formData.append('mailSys', mailSys);
The above is the detailed content of How to use el-upload to upload files in vue3. For more information, please follow other related articles on the PHP Chinese website!