기술나눔

element 如何实现文件上传下载导出

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

上传:

前端:

  1. <div>
  2. <el-dialog
  3. title="低值易耗文件上传"
  4. :visible.sync="dialogUploadVis"
  5. width="25%"
  6. >
  7. <el-upload
  8. class="upload-demo"
  9. drag
  10. :on-change="handleChange"
  11. :file-list="upload.fileList"
  12. :multiple="false"
  13. :auto-upload="false"
  14. :http-request="uploadFile"
  15. action="string"
  16. ref="upload"
  17. >
  18. <i class="el-icon-upload"></i>
  19. <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
  20. <div class="el-upload__tip" slot="tip" style="text-align: center;">
  21. 仅允许导入xlsx、xls格式文件。
  22. <el-link type="primary" :underline="false">下载模板</el-link>
  23. </div>
  24. </el-upload>
  25. <span slot="footer" class="dialog-footer">
  26. <el-button type="primary" @click="uploadButSubmit">确 定</el-button>
  27. <el-button @click="dialogUploadVis = false">取 消</el-button>
  28. </span>
  29. </el-dialog>
  30. </div>
  31. <script>
  32. data(){
  33. return(
  34. upload: {
  35. fileList: [],
  36. formData: ''
  37. },
  38. )}
  39. methods: {
  40. submitUpload() {
  41. this.$refs.upload.submit()
  42. },
  43. delFile() {
  44. this.fileList = []
  45. },
  46. handleChange(file, fileList) {
  47. this.fileList = fileList
  48. },
  49. //自定义上传文件
  50. uploadFile(file) {
  51. //this.formData.append("file", file.file);
  52. },
  53. //保存按钮
  54. async uploadButSubmit() {
  55. let formData = new FormData()
  56. console.log(this.fileList)
  57. formData.append('file', this.fileList[0].raw) //拿到存在fileList的文件存放到formData中
  58. await ****(formData)
  59. .then(res => {
  60. this.$message({
  61. message: res,
  62. type: 'success'
  63. })
  64. this.$emit('closeUpload')
  65. })
  66. .catch(res => {
  67. this.$message({
  68. message: res,
  69. type: 'error'
  70. })
  71. })
  72. },}
  73. </script>

下载:

导出:

前端:

  1. <div>
  2. <el-button type="warning" @click="downloadBut"
  3. ><i class="el-icon-download"></i> 导出</el-button>
  4. </div>
  5. //api
  6. //requestMultipart 为文件请求方式
  7. export function ****() {
  8. return requestMultipart({
  9. url: '*****',
  10. method: 'get',
  11. params: {
  12. *****
  13. },
  14. responseType: 'blob'
  15. })
  16. }
  17. //npm install file-saver --save
  18. import FileSaver from 'file-saver'
  19. <script>
  20. async downloadBut() {
  21. await *****()
  22. .then(res => {
  23. FileSaver.saveAs(
  24. new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' }),
  25. `低值易耗.xlsx`
  26. )
  27. })
  28. .catch()
  29. },
  30. </script>