当前位置:   article > 正文

Vue+Element-UI 文件导入导出get和post请求方式_el-form发送post请求

el-form发送post请求

post请求方式:    

   1、手动上传并自带参数

  1. <el-form-item label="上传">
  2. <el-upload
  3. ref="upload"
  4. class="upload-demo"
  5. :auto-upload="false" //是否在选取文件后立即进行上传
  6. :http-request="import" //覆盖默认的上传行为,可以自定义上传的实现
  7. :data="data" //需传递的数据
  8. action="no">
  9. <el-button size="small" type="primary">选取文件</el-button>
  10. </el-upload>
  11. </el-form-item>
  12. <el-form-item label="">
  13. <el-button type="primary" @click="submitUpload">导入</el-button>
  14. <el-button type="primary" @click="cancel">取消</el-button>
  15. </el-form-item>
  16. submitUpload() {
  17. this.$refs.upload.submit() // 手动上传文件列表
  18. },
  19. import(val) {
  20. const fd = new FormData()
  21. fd.append('data', JSON.stringify(val.data))
  22. fd.append('file', val.file)
  23. import(fd).then(res => { //向后请求
  24. console.log('导入成功')
  25. })
  26. }

 后端代码如下

  1. @PostMapping("import")
  2. public void import(@RequestParam("file") MultipartFile file, @RequestParam("data") String json) {
  3. try {
  4. Entity entity= JSON.parseObject(json, Entity .class);
  5. //操作文件
  6. } catch (Exception e) {
  7. e.printStackTrace();
  8. }
  9. }

2、自动上传

  1. <el-form ref="form" :model="form" :rules="rules" size="small">
  2. <el-upload
  3. :action="uploadApi"
  4. :headers="headers"
  5. :on-success="handleSuccess"
  6. :on-error="handleError"
  7. class="upload-demo"
  8. drag>
  9. <i class="el-icon-upload" />
  10. <div class="el-upload__text">
  11. 将文件拖到此处,或
  12. <em>点击上传</em>
  13. </div>
  14. </el-upload>
  15. </el-form>
  16. export default {
  17. data() {
  18. return {
  19. uploadApi: process.env.VUE_APP_BASE_API+ '/upload'
  20. }
  21. },
  22. methods: {
  23. cancel() {
  24. this.resetForm()
  25. },
  26. handleSuccess(response, file, fileList) {
  27. this.cancel()
  28. },
  29. // 监听上传失败
  30. handleError(e, file, fileList) {
  31. const msg = JSON.parse(e.message)
  32. this.$notify({
  33. title: msg.message,
  34. type: 'error',
  35. duration: 2500
  36. })
  37. }
  38. }
  39. }

后端代码如下

  1. @PostMapping(value = "/upload")
  2. public ResponseEntity<Object> upload(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
  3. //解析操作文件
  4. }

3、导出

  1. export default {
  2. name: 'Cadata',
  3. inject: ['reload'],
  4. data() {
  5. return {},
  6. }
  7. },
  8. methods: {
  9. export() {
  10. data.exportData(data).then(res => {
  11. if (res != null) {
  12. this.downloadFile(res, this.caname, '.p12')
  13. // this.reload();
  14. }
  15. }).catch(() => {
  16. this.loading = false
  17. })
  18. },
  19. downloadFile(obj, name, suffix) {
  20. const url = window.URL.createObjectURL(new Blob([obj], {type: 'application/x-pkcs12'}))
  21. const link = document.createElement('a')
  22. link.style.display = 'none'
  23. link.href = url
  24. const fileName = name + suffix
  25. link.setAttribute('download', fileName)
  26. document.body.appendChild(link)
  27. link.click()
  28. document.body.removeChild(link)
  29. }
  30. }
  31. }
  32. js:
  33. export function exportData(data) {
  34. return request({
  35. url: 'api/exportData',
  36. method: 'post',
  37. data: data,
  38. responseType: 'blob',
  39. headers: {
  40. 'Content-Type': 'application/x-pkcs12' // 请求的数据类型为form data格式
  41. }
  42. })

后台代码

  1. @PostMapping("exportData")
  2. public void exportData(@RequestBody Entity entity, HttpServletResponse res, HttpServletRequest req) {
  3. try {
  4. byte[] bytes ; //获取要导出数据
  5. String encoding = req.getCharacterEncoding();
  6. if (StringUtils.isEmpty(encoding)) {
  7. encoding = "UTF-8";
  8. }
  9. req.setCharacterEncoding(encoding);
  10. res.setContentType("application/octet-stream");
  11. res.setHeader("Content-disposition", "attachment; filename=\"" + StringTools.stripFilename(caname + ".p12") + "\"");
  12. log.info("======导出结束======");
  13. } catch (Exception e) {
  14. log.error("error:" + e);
  15. } finally {
  16. if (inputStream != null) {
  17. try {
  18. inputStream.close();
  19. // if (deleteOnExit) {
  20. // file.deleteOnExit();
  21. // }
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }
  27. }

get请求方式

1、导出

  1. down(data) {
  2. cafunctions.download(data.caid).then(res => {
  3. this.downPemFile(res, name, 'pem') //和导出方法一样
  4. })
  5. }
  6. js:
  7. export function download(caid) {
  8. return request({
  9. url: 'api/certificatedata/downloadJks?caid=' + caid ,
  10. method: 'get',
  11. responseType: 'blob'
  12. })
  13. }

后台代码如下

  1. /**
  2. * 导出excel
  3. */
  4. @GetMapping(value = "/download")
  5. public void downloadExcel(int caid, HttpServletResponse response) throws IOException {
  6. String tempPath = System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
  7. File file = new File(tempPath);
  8. BigExcelWriter writer = ExcelUtil.getBigWriter(file);
  9. // 一次性写出内容,使用默认样式,强制输出标题
  10. List<Map<String, Object>> list=null; //获取要导出的数据
  11. writer.write(list, true);
  12. //response为HttpServletResponse对象
  13. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
  14. //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
  15. response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");
  16. ServletOutputStream out = response.getOutputStream();
  17. // 终止后删除临时文件
  18. file.deleteOnExit();
  19. writer.flush(out, true);
  20. //此处记得关闭输出Servlet流
  21. IoUtil.close(out);
  22. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/227677
推荐阅读
相关标签