Home  >  Article  >  Web Front-end  >  How to use el-upload to upload files in vue3

How to use el-upload to upload files in vue3

WBOY
WBOYforward
2023-05-15 21:31:043282browse

el-upload Upload files

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.

Attributes

  • 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

Method

  • 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.

Implementation of uploading pictures

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=&#39;limit&#39;
      :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: &#39;uploadImg&#39;
}
</script>
<script setup>
import { Delete, Plus, ZoomIn } from &#39;@element-plus/icons-vue&#39;;
import { reactive, ref, defineProps, defineEmits, computed, getCurrentInstance } from &#39;vue&#39;;
import { ElMessage } from &#39;element-plus&#39;;
const props = defineProps({
  // 允许上传文件件的最大数量
  limit:{
    type:Number
  },
  // 是否禁用上传
  disabled:{
    type:Boolean,
    default:false
  },
  // 文件列表类型
  listType:{
    type:String,
    default:&#39;picture-card&#39;
  },
  // 上传时携带的额外参数
  paramData: {
    type:String
  }
});
const emits = defineEmits([]);
const cns = getCurrentInstance();
const globObj = cns.appContext.config.globalProperties;
const previewVisible = ref(false);
const dialogImageUrl = ref(&#39;&#39;);
const fileListCopy = reactive({
  data: []
});
const onece = ref(false);
const myChangeFile = ref(&#39;&#39;);
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(&#39;handleRemove&#39;, handleRemove);
  console.log(&#39;file&#39;, file);
  console.log(&#39;fileList&#39;, fileList);
  fileListCopy.data = fileListCopy.data.filter(v => v.uid !== file.uid);
};
// 文件上传数量限制
const handleExceed = (files, fileList) => {
  if (props.limit) {
    ElMessage.error(`只能上传${props.limit}张图片`);
  }
  console.log(&#39;handleExceed&#39;, handleExceed);
  console.log(&#39;files&#39;, files);
  console.log(&#39;fileList&#39;, fileList);
};
// 上传请求
const uploadAction = (option) => {
  let formData = new FormData();
  const url = &#39;&#39;;
  globObj.$axios({
    url: url,
    method: &#39;post&#39;,
    transformRequest: [function(data, headers) {
      // 去除post请求默认的Content-Type
      delete headers[&#39;Content-Type&#39;]
      return data
    }],
    data: formData,
    timeout: 300000
  }).then(res => {
    ElMessage.success(&#39;资产添加成功&#39;);
  }).catch((err) => {
    console.log(err);
  });
}
// 格式大小的限制
const beforeUpload = (file) => {
  let isJPG = false,
  fileType = file.type.split(&#39;/&#39;)[0];
  if(file.type === "image/jpeg" || file.type === "image/png") {
    isJPG = true;
  } else {
    isJPG = false;
  }
  const isLt2M = file.size / 1024 / 1024;
  if (fileType != &#39;image&#39; || isLt2M > 2) {
    ElMessage.error("请上传2M以内的图片文件!");
    return false
  }
  return true;
};
// 文件上传成功时的钩子
const uploadSuccess = (response, file, fileList) => {
  // 上传成功之后后台返回的数据
  console.log(&#39;uploadSuccess&#39;, uploadSuccess);
};
const uploadProgress = (e, file, fileList) => {
  console.log(&#39;uploadProgress&#39;, uploadProgress)
};
const uploadError = (err, file, fileList) => {
  console.log(&#39;uploadError&#39;, uploadError);
};
</script>

Existing pits

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.

Question 1

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

Question 2

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: &#39;post&#39;,
    transformRequest: [function(data, headers) {
      // 去除post请求默认的Content-Type
      delete headers[&#39;Content-Type&#39;]
      return data
    }],
    data: formData,
    timeout: 300000
  }).then(res => {
    ElMessage.success(&#39;资产添加成功&#39;);
  }).catch((err) => {
    console.log(err);
  });

Question 3

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(&#39;file&#39;, file);
// 其他参数
formData.append(&#39;mailSys&#39;, 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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete