当前位置:网站首页>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 URLshow-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

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

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>

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>

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>

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>

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>

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

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>

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 .

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 ",
});
}
});
}

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);
};
边栏推荐
- Xcall cluster script (view JPS command)
- matplotlib. pyplot. Bar chart (II)
- Explore performance optimization! Performance improvement from 2 months to 4 hours!
- 力扣解法汇总821-字符的最短距离
- Summary of force deduction solution 944- deletion of sequence
- ozzanimation-基於sse的動作系統
- 超图倾斜数据合并根节点后转3dtiles
- 【无标题】2022煤矿安全检查考题及在线模拟考试
- C language programming classic games - minesweeping
- Linux(CentOS7)安裝MySQL-5.7版本
猜你喜欢

How to maximize the use of various matching methods—— Google SEM

leetcode:6. Zigzag transformation

SQL calculates KS, AUC, IV, psi and other risk control model indicators

leetcodeSQL:612. Nearest distance on plane

matplotlib. pyplot. Bar chart (II)

Glfwpollevents() program crash

Smartbi helps you solve the problem of losing high-value customers

程序员应该如何解决买菜难问题?手把手带你利用无障碍辅助功能快速下单抢菜

MySQL advanced knowledge points

RPA introduction
随机推荐
力扣解法汇总944-删列造序
Installing MySQL version 5.5 database for Linux (centos6)
C language programming classic games - minesweeping
力扣解法汇总面试题 17.11-单词距离
xcall 集群脚本(查看jps命令)
Force deduction solution summary 942- increase / decrease string matching
android html5页面加载缓存优化
MySQL高级部分知识点
Force deduction solution summary 462- minimum number of moves to make array elements equal II
Graphic data analysis | data cleaning and pretreatment
Is there a female Bluetooth headset suitable for girls? 38 Bluetooth headsets worth getting started
Ozzanmation action system based on SSE
Force deduction solution summary 953 verification of alien language dictionary
Oracle 11g graphic download installation tutorial (step by step)
Force deduction solution summary 473 match to square
Force deduction solution summary 668- the smallest number k in the multiplication table
"China Dongxin Cup" the fourth programming competition of Guangxi University (synchronous competition)
A mystery of the end of vagrant up
How to locate keywords to make advertising accurate.
How WPS inserts a directory and the operating steps for quickly inserting a directory