当前位置:网站首页>Upload Excel files with El upload and download the returned files
Upload Excel files with El upload and download the returned files
2022-07-29 00:29:00 【qiansli12138】
demand :vue Upload excel File to background , And download new files .
step :
1. establish html page , It's used here dialog bounced , If it is a form, modify it by yourself .
<el-dialog title=" Export the specified physical examination information " :visible.sync="dialogVisibleexptbyfile" width="50%" center :append-to-body="true">
<div class="submit">
<el-form :model="form" label-width="140px" label-position="left">
<el-form-item label=" type ">
<el-select v-model="form.type" placeholder=" Please choose the type ">
<el-option label=" Medical examination No " value="0"></el-option>
<el-option label=" ID number " value="1"></el-option>
</el-select>
</el-form-item>
<el-form-item label=" Select File ">
<el-upload class="upload-demo" :limit="1" :on-exceed="exceedfile" :headers="{headers: 'multipart/form-data'}" action="#" :on-change="onChangefile" :before-upload="beforeuploadfile" :auto-upload='false' :before-remove="removefile" :file-list="fileList">
<el-button size="small" type="primary"> Click upload </el-button>
</el-upload>
<div class="el-upload__tip"> Can only upload XLS,XLSX File format , Data cannot exceed 4500 strip </div>
<!-- <input type="file" id="file" ref="file"> -->
</el-form-item>
<el-form-item label=" Select row data ">
<el-input v-model="form.startRow" style="width: 52%;"></el-input>
</el-form-item>
<el-form-item label=" choice Column ">
<el-input v-model="form.colNum" style="width: 52%;"></el-input>
</el-form-item>
</el-form>
<!-- <form action="http://192.168.1.49:5001/yt/tjeBf/" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="elFile" />
<input type="submit" value=" Submit ">
</form> -->
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisibleexptbyfile = false"> take eliminate </el-button>
<el-button type="primary" @click="exptbyfile"> indeed set guide Out </el-button>
</span>
</el-dialog>2.el-upload There are many callback methods above , You can have a look , Here are a few .
2.1 :limit="1" :on-exceed="exceedfile".limit Used to limit the number of files ,on-exceed For more than limit Quantity operation .
exceedfile () {
this.$message.warning(' Only one file can be uploaded , Please delete and add !')
},2.2:headers="{headers: 'multipart/form-data'}". Set the upload request header .
2.3:on-change="onChangefile". The function triggered when the file changes . You can verify the file type , Include file size , Format, etc . I saved the file data here .
onChangefile (file) {
// file Document change
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
// Here I need to upload the form file , So there are restrictions
if (['xls', 'xlsx'].indexOf(testmsg.toLowerCase()) == -1) {
this.$message.warning(' Can only upload .XLS.XLSX File format !')
this.fileList.shift()
return
}
// Take the selected file to , Here we need to write according to our own business
this.fileList[0] = file
this.file = file.raw
this.filename = file.name
},2.4:before-upload="beforeuploadfile".
2.5:auto-upload='false'. Avoid automatic uploading . meanwhile action Set to “#”, Can be any value .
2.6:before-remove="removefile". Used to empty the file list array , Avoid deleting files, but there are still cases in the array .
removefile () {
this.fileList = []
},2. After the above is done, you can click OK to jump to the uploaded part . perform enterfile Function of . It's used here formData To store file type data and other data .formData Take a look at this (FormData - Web API Interface reference | MDNFormData Interface provides a key value pair to represent form data key/value Mode of construction , And it's easy to pass data through XMLHttpRequest.send() Method send out , This interface and this method are quite simple and direct . If the encoding type at the time of sending is set to "multipart/form-data", It will use the same format as the form .
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData)
exptbyfile () {
// Some judgments about the data
if (this.fileList.length == 0) {
Utils.showTis(' Please upload the file ', 'warning')
return
}
if (this.form.type == "") {
Utils.showTis(' Please choose the type ', 'warning')
return
}
if (this.form.sheetIndex == "") {
Utils.showTis(' Please enter the number of lines ', 'warning')
return
}
if (this.form.colNum == "") {
Utils.showTis(' Please enter the number of columns ', 'warning')
return
}
const formData = new FormData() //FormData object , Adding parameters can only be done through append('key', value) In the form of
formData.append('file', this.file) // Add file object
// Call upload interface
let userinfo = User.getData("userInfo");
var params = {
type: this.form.type,
sheetIndex: this.form.sheetIndex,
startRow: this.form.startRow,
colNum: this.form.colNum,
token: userinfo.token,
cid: userinfo.cid
};
this.downLoadFile(this.file, "yt/tjeBf", params, document.getElementById("file"))
.then(res => {
this.dialogVisibleexptbyfile = false
if (res.code) {
Utils.showTis(res.msg, 'warning')
}
}).catch(() => {
this.dialogVisibleexptbyfile = false
})
},
downLoadFile (res, url, params = {}) {
return new Promise((resolve, reject) => {
let loadingInstance = this.$loading({
lock: true,
text: ' Uploading …',
background: 'rgba(0, 0, 0, 0.3)'
});
let userinfo = User.getData("userInfo");
var formData = new FormData();
formData.append("token", userinfo.token);
formData.append("cid", userinfo.cid);
formData.append("file", res);
for (var i in params) {
formData.append(i, params[i]);
}
$.ajax({
url: Config.gw.base + url,
type: "POST",
data: formData,
cache: false, // Upload files without caching
processData: false, // Used to deal with data Parameters are serialized It has to be here false
contentType: false, // must */
xhrFields: { responseType: "blob" }, // The data type returned is Blob type
success: function (data) {
loadingInstance.close();
if (data.code) {
// showTis(" Upload error ", data.msg)
resolve(data)
} else {
let url = window.URL.createObjectURL(new File([data], res.name))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', ` Medical examination list file ${new Date().getFullYear()}${new Date().getMonth() + 1}${new Date().getDate()}${new Date().getHours()}${new Date().getMinutes()}${new Date().getSeconds()}.xlsx`)
document.body.appendChild(link)
link.click()
// Release URL Resources occupied by objects
window.URL.revokeObjectURL(url)
// // Delete when used up
document.body.removeChild(link)
resolve(data)
}
},
error: function (error, err2, err3) {
loadingInstance.close();
showTis(" Upload error , Please contact the Administrator ")
reject(error)
}
});
})
}Download with a The method of linking , establish a Link to url that will do . The method is as follows ( It has ):
let url = window.URL.createObjectURL(new File([data], res.name))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', ` Medical examination list file ${new Date().getFullYear()}${new Date().getMonth() + 1}${new Date().getDate()}${new Date().getHours()}${new Date().getMinutes()}${new Date().getSeconds()}.xlsx`)
document.body.appendChild(link)
link.click()
// Release URL Resources occupied by objects
window.URL.revokeObjectURL(url)
// // Delete when used up
document.body.removeChild(link)I wonder if the record is clear , It's best to use it directly next time !
边栏推荐
- ACM SIGIR 2022 | interpretation of selected papers of meituan technical team
- [CNN] Why is the convolution kernel size of CNN usually odd
- @Transactional 注解使用详解
- CV semantic segmentation model sketch (2)
- Multimodal model sketch (1)
- Summary: the difference between pod and container
- What does WGet mean
- PTA (daily question) 7-73 turning triangle
- Dynamic programming problem (4)
- Applet verification code login
猜你喜欢

flyway的快速入门教程

Oracle实例无法启动的问题如何解决

Attack and defense world web master advanced area php2
![[ESN] learning echo state network](/img/8e/09cc2d2c0e0ee24e9bee13979b03cb.png)
[ESN] learning echo state network

Field injection is not recommended solution

Use hutool tool class to operate excel with more empty Sheet1

“吃货联盟定餐系统”

Sword finger offer 64. find 1+2+... +n, logical operator short circuit effect

PTA (daily question) 7-75 how many people in a school

Laravel8 middleware realizes simple permission control
随机推荐
@Detailed explanation of the use of transactional annotation
flyway的快速入门教程
"Method not allowed", 405 problem analysis and solution
Alibaba Code代码索引技术实践:为Code Review提供本地IDE的阅读体验
Dynamic programming problem (6)
What does WGet mean
PTA (daily question) 7-73 turning triangle
Attack and defense world web master advanced area php2
MySQL 分库分表及其平滑扩容方案
Advanced area of attack and defense world web masters unserialize3
[micro services ~nacos] Nacos service providers and service consumers
IDEA2021.2安装与配置(持续更新)
16.偏差、方差、正则化、学习曲线对模型的影响
Advanced area of attack and defense world web masters warmup
动态规划问题(二)
Compilation principle research study topic 2 -- recursive descent syntax analysis design principle and Implementation
Sword finger offer 41. median in data flow
动态规划问题(三)
How to learn R language
CV target detection model sketch (2)