当前位置:网站首页>El upload upload file

El upload upload file

2022-06-12 02:11:00 Red blue purple

el-upload Upload files

Preface

Both company and school projects use the function of uploading files , Make a note of .

Get ready

express Implemented upload interface

const express = require('express');
​
//  File upload module 
const multiparty = require('multiparty')
​
//  Provide cross domain resource requests 
const cors = require('cors')
​
//  File operations 
const fs = require('fs')
​
const app = express();
​
app.use(cors());
​
app.get('/policy', (req, res) => {
  res.json({
    code: 200,
    msg: ' success ',
    url: '/upload',
    filename: 'clz'
  })
});
​
app.post('/upload', (req, res) => {
  let form = new multiparty.Form()
​
  //  Configuration file storage path 
  form.uploadDir = './upload'
​
  form.parse(req, (err, fields, files) => {
    //  analysis formData
​
    for (const file of files.file) {
      const newPath = form.uploadDir + '/' + file.originalFilename
​
      // renameSync(oldPath, newPath): Sync rename file ,oldPath Use the default upload path ,newPath Is the path you want to save to 
      fs.renameSync(file.path, newPath);
    }
​
    res.json({
      code: 200,
      msg: ' Upload successful '
    })
  })
});
​
app.listen(8088, () => {
  console.log('http://localhost:8088/');
});

If needed , Self access express usage , You can also go to My blog View a simple tutorial in .

Start

Easy to use version

<template>
  <el-upload
    action="http://localhost:8088/upload"
    :show-file-list="true"
    :on-success="handleSuccess"
    :on-error="handleError"
  >
    <el-button type="primary"> To upload pictures </el-button>
  </el-upload>
</template>
​
<script setup>
import { ElMessage } from "element-plus";
​
const handleSuccess = (res, file, files) => {
  console.log(res);
  console.log(file, files);
​
  new ElMessage({
    type: "success",
    message: " Upload successful ",
  });
};
​
const handleError = (error, file, files) => {
  console.log(error);
  console.log(file, files);
  ElMessage.error(" Upload failed ");
};
</script>
​
<style lang="less" scoped>
</style>
​

Explain the properties above :

  • action: request URL

  • show-file-list: Whether to expand the document list ( If the upload fails , Will flash , Disappear again )

  • on-success: File upload successful hook

    • Parameters :
    • res: The successful response data returned by the backend ( When the response status is success )
    • file: Uploaded files
    • files: List of successfully uploaded files
  • on-success: File upload failed hook

    • Parameters :
    • error: Error object , The content is the response data returned by the backend ( When the response status is failed , If the status code is 500)
    • file: Uploaded files
    • files: List of successfully uploaded files

file

Next , Go to the path set at the back end to see if the uploaded file has been saved successfully .

image-20220508120156380

add to token

This is simpler , because element-plus It's also sealed , Just use headers attribute , Set the request header

<el-upload
  action="http://localhost:8088/upload"
  :headers="{ token: '12345' }"
>
  <el-button type="primary"> To upload pictures </el-button>
</el-upload>

image-20220508120607213

Get the signature before uploading

Sometimes you can't just upload it directly , For example, there was no upload path at first , You need to call the get signature interface to get the upload path . At this time, you can use our hook before uploading files before-upload. Call the interface to get the signature before uploading , Use what you get url To modify , Upload path , You can upload .

<template>
  <el-upload :action="url" :before-upload="getPolicy">
    <el-button type="primary"> To upload pictures </el-button>
  </el-upload>
</template>
​
<script setup>
import axios from "axios";
import { reactive, ref } from "vue";
​
const url = ref("");
​
const getPolicy = () => {
  return new Promise((resolve, reject) => {
    axios
      .get("http://localhost:8088/policy")
      .then((res) => {
        const { data } = res;
​
        if (data.code === 200) {
          url.value = `http://localhost:8088${data.url}`;
​
          resolve();
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};
</script>
​
<style lang="less" scoped>
</style>

image-20220508134523663

Manually upload

In the above examples, the file is selected , Will upload , But sometimes we need to click the button to upload , This time we need to combine auto-upload and submit To realize manual uploading . First set up auto-upload by false, Cancel automatic upload , At this time, the selected image will not be uploaded , So we are in the click event of the button , You have to use DOM To call submit Methods to upload manually .

<template>
  <el-upload
    ref="upload"
    action="http://localhost:8088/upload"
    :auto-upload="false"
  >
    <el-button type="primary"> To upload pictures </el-button>
  </el-upload>
​
  <el-button type="primary" @click="confirm"> determine </el-button>
</template>
​
<script setup>
import { getCurrentInstance } from "vue";
​
const { proxy } = getCurrentInstance();
​
const confirm = () => {
  proxy.$refs.upload.submit();
};
</script>
​
<style lang="less" scoped>
</style>

file

Modify the file name when uploading

situation : When calling the signature interface, a file name will also be returned , The front end needs to change the file name before uploading , Let the server save the standard file name .

First , Let's start with the conclusion : Cannot modify File Object's name attribute , Implement rename

Modify in the hook before uploading File Object's name attribute

<template>
  <el-upload
    action="http://localhost:8088/upload"
    :before-upload="getPolicy"
  >
    <el-button type="primary"> To upload pictures </el-button>
  </el-upload>
</template>
​
<script setup>
//  Pre upload hook 
const getPolicy = (file) => {
  console.log(file);
​
  file.name = "clz.png";    //  If the file is checked in the hook before uploading name Property to modify , It will not upload . And don't make a mistake , It is difficult to find the problem .
​
  console.log(file.name);
};
</script>
​
<style lang="less" scoped>
</style>

file

Without waves .

Modify when uploading files

adopt http-request attribute , Override the default upload behavior .

<template>
  <el-upload action="http://localhost:8088/upload" :http-request="httpRequest">
    <el-button type="primary"> To upload pictures </el-button>
  </el-upload>
</template>
​
<script setup>
const httpRequest = ({ file }) => {
  console.log(file);
  file.name = "clz.png";
};
</script>
​
<style lang="less" scoped>
</style>

file

Direct error

Solution

Since it cannot be modified directly File Object's name Property to implement the rename operation , So what should I do ?

This is the time to pass new File Constructor to create another file , Change the name while creating .

<template>
  <el-upload action="http://localhost:8088/upload" :http-request="httpRequest">
    <el-button type="primary"> To upload pictures </el-button>
  </el-upload>
</template>
​
<script setup>
const httpRequest = ({ file }) => {
  console.log(file);
​
  const cloneFile = new File([file], "clz.png");
​
  console.log(cloneFile);
};
</script>
​
<style lang="less" scoped>
</style>

Be careful : If you change the file name of a file ,File The first argument to the constructor of should be to enclose file Array of

image-20220508164215907

But at this point , There's another problem , We've used http-request Overwrite the default upload behavior , So we have to upload again .

Uploading a file first requires formData object , And then to formData Add upper data , In the formData Send it through the interface .

<template>
  <el-upload action="#" :http-request="httpRequest">
    <el-button type="primary"> To upload pictures </el-button>
  </el-upload>
</template>
​
<script setup>
import axios from "axios";
import { ElMessage } from "element-plus";
​
const httpRequest = ({ file }) => {
  console.log(file);
​
  const cloneFile = new File([file], "clz.png");
​
  const formData = new FormData();
  formData.append("file", cloneFile);
​
  axios.post("http://localhost:8088/upload", formData).then((res) => {
    if (res === 200) {
      new ElMessage({
        type: "success",
        message: " Upload successful ",
      });
    }
  });
};
</script>
​
<style lang="less" scoped>
</style>

image-20220508165110118

Tips:

The solution has been mentioned above , however , Renaming doesn't usually help you change the file suffixes . So you can get the suffix through regular expression at this time .

const houzhui = file.name.replace(/.+./, "");
const newFile = new File([file], filename+houzhui);

Request to upload multiple files at once

el-upload By default, one file is uploaded per request . To upload multiple files, you must first add multiple attribute .

file

In the example above , We can find out , We selected two files above , Click ok , The upload interface is called twice when uploading pictures .

since el-upload By default, one file is uploaded per request , Then let's not use el-upload The upload method is OK . When you click the OK button , To call an upload file method .

Because when we click OK , You need to get the selected file , So there needs to be file-list attribute , Save the selected file .

<template>
  <el-upload
    ref="upload"
    action="#"
    multiple
    :file-list="fileList"
    :auto-upload="false"
  >
    <el-button type="primary"> To upload pictures </el-button>
  </el-upload>
​
  <el-button type="primary" @click="confirm"> determine </el-button>
</template>

Click the OK button , Will trigger confirm event , This is the key to implementing a request to upload multiple files , This is the time to create a formData object , Traverse the selected file list , adopt append Add to formData On . Finally, I call uploadFile function , Actually upload the file .

const fileList = reactive([]);
​
const confirm = () => {
  const formData = new FormData();
​
  console.log(fileList);
​
  for (const file of fileList) {
    formData.append("file", file.raw);
  }
​
  uploadFiles(formData);
};
​
function uploadFiles(data) {
  axios.post("http://localhost:8088/upload", data).then((res) => {
    if (res === 200) {
      new ElMessage({
        type: "success",
        message: " Upload successful ",
      });
    }
  });
}

file

Small skills

Get the width and height pixels of the picture

//  establish Image object 
const img = new Image();
​
//  Set up the src
img.src = 'https://www.clzczh.top/medias/featureimages/19.png';
​
//  add to load event , Execute after the picture is loaded 
img.onload = () => {
  //  Get the width and height pixels of the picture 
  console.log(img.width, img.height);
};
原网站

版权声明
本文为[Red blue purple]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120206540894.html