JS implements file upload (file import)

File upload is implemented in vue through el-upload of element-plus library.

1. Request

axios({
    
    
  url: '#',
  headers: {
    
    
    'Content-Type': 'multipart/form-data'
  },
  method: 'post',
  data: {
    
    } // 需要上传的文件内容
})

Take the axios request as an example. For the file upload interface, the upload request type must be multipart/form-data, and the uploaded content is no longer The parameter is used to pass in the file. json format, but a file type. data

2. HTML

1. Here I put the uploaded file in a el-dialog pop-up box, open the pop-up box and transfer the file, and then click OK to upload.
2. If you don’t need a pop-up box, just ignore the step of pop-up box.
3. If you want to upload the file automatically without clicking the button after it is passed in, please set it yourself action or read other articles. This article is of little reference significance.

<!--   导入   -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <el-upload
          ref="importRef"
          :limit="1"
          action="#"
          accept=".xlsx, .xls"
          :on-remove="(file, fileList) => {removeImportFile(file, fileList)}"
          :on-change="(file, fileList) => (changeImportFile(file, fileList))"
          :on-exceed="exceedImportFile"
          :auto-upload="false"
          drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>

el-uploadThe meaning of some attributes:

  • ref: Convenient to obtain DOM nodes in vue
  • Limit: Limit the number of files uploaded at one time. Only one file can be uploaded at a time. If you want to upload multiple files, modify it by yourself in the file acquisition and interface upload.
  • action: Request URL. I am manually requesting the upload with a button instead of automatically uploading the file after passing in the file through the action of the component itself, so this part is useless. You can delete it, or you can pass a # like I did.
  • accept: Accept the uploaded file type (this parameter is invalid in thumbnail-mode mode). I am lazy and use the component itself to determine the type. In fact, I can judge the file type by myself when passing in the file. It's not processed, it's simpler, and there's no control over the file size or anything like that.
  • on-remove: Hook when removing files from the file list
  • on-change: hook when the file status changes. It will be called when adding files, uploading successfully and uploading fails.
  • on-exceed: The hook function executed when the limit is exceeded
  • auto-upload: whether to automatically upload files
  • drag: Whether to enable drag and drop uploading

importTemplate()Depending on the actual needs, the click event of downloading the template does not require template operation. I have added the download operation of the template here, and delete it if it is not needed.

3. JS

1. I am using vue3 here. If you don’t understand it, just take a look at it. In fact, it is not much different from vue2.

// 导入
const upload = reactive({
    
    
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: ''
})
let fileFormData = reactive(null)

// 监听导入弹框关闭的时候清空列表,防止下次打开文件还在
watch(() => upload.open, () => {
    
    
  if (!upload.open) {
    
    
    proxy.$refs.importRef.clearFiles()
    fileFormData = null
  }
})

// 点击导入按钮,打开弹框
function handleImport () {
    
    
  upload.open = true
  upload.title = '导入'
}

// 移除导入的文件
function removeImportFile (file, fileList) {
    
    
  proxy.$refs.importRef.clearFiles()
  fileFormData = null
}

// 更改导入的文件
function changeImportFile (file, fileList) {
    
    
  fileFormData = new FormData()
  fileFormData.append('file', file.raw)
}

// 上传文件超出个数
function exceedImportFile () {
    
    
  ElMessage.error('文件个数超出限制,请先移除上一个文件')
}

// 下载导入模板
function importTemplate () {
    
    
  const a = document.createElement('a')
  a.href = '可直接下载的链接,如OSS链接'
  a.download = '导入模板.xls'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 导入文件上传
function submitFileForm () {
    
    
  if (fileFormData) {
    
    
  axios({
    
    
  	url: '#',
 	headers: {
    
    
    	'Content-Type': 'multipart/form-data'
  	},
 	method: 'post',
  	data: fileFormData // 需要上传的文件内容
	}).then(rea => {
    
    
		upload.open = false
	})
  }
}

The most critical part of file upload here is to create a FormData object and pass the file file to the server in the form of key-value pairs.

Guess you like

Origin blog.csdn.net/qq_43651168/article/details/130271014