<template>
<div>
<el-upload
class="image-uploader"
:multiple="false"
:auto-upload="true"
list-type="text"
:show-file-list="true"
:before-upload="beforeUpload"
:drag="true"
action
:limit="1"
:on-exceed="handleExceed"
:http-request="uploadFile"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
<div class="el-upload__tip" slot="tip">一次只能上传一个文件,仅限text格式,单文件不超过1MB</div>
</el-upload>
</div>
</template>
<script>
import upload from '@/api/upload'
export default {
data() {
return {
test: 123
};
},
methods: {
beforeUpload(file) {
console.log("beforeUpload");
console.log(file.type);
// Text文件格式
// const isText = file.type === "application/vnd.ms-excel";
//Excel 文件格式
const isTextComputer =
file.type ===
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if(!isTextComputer){
this.$message.warning(`只能上传excel格式文件`);
}
return isTextComputer
// return isText | isTextComputer;
},
// 上传文件个数超过定义的数量
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,请删除后继续上传`);
},
// 上传文件
uploadFile(item) {
console.log(item);
const fileObj = item.file;
console.log(fileObj)
// FormData 对象
const form = new FormData();
// 文件对象
form.append("file", fileObj);
upload.excel(form).then(res=>{
console.log(res)
if (res === "success"){
this.$message.success(`上传成功`);
}
})
}
}
};
</script>
<style lang="scss" scoped>
</style>
package com.gpdi.springbootshirojwt.controller;
import com.gpdi.springbootshirojwt.config.R;
import com.gpdi.springbootshirojwt.utils.ExcelUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @Description:
* @Author: Lxq
* @Date: 2019/12/22 9:29
*/
@RestController
@RequestMapping("/api")
public class TestController {
@PostMapping("/uploadExcel")
public R userLogout(@RequestParam(value = "file")MultipartFile file) throws IOException {
System.out.println(file.getName());
System.out.println(file.getOriginalFilename());
System.out.println(file.getContentType());
System.out.println(file.getSize());
InputStream inputStream = file.getInputStream();
List<Object> objects = ExcelUtils.readLessThan1000RowBySheetAndStream(inputStream, null);
System.out.println(objects);
return R.ok("success");
}
}