post请求方式:    

   1、手动上传并自带参数

<el-form-item  label="上传">
    <el-upload
      ref="upload"
      class="upload-demo"
      :auto-upload="false"    //是否在选取文件后立即进行上传
      :http-request="import"  //覆盖默认的上传行为,可以自定义上传的实现
      :data="data"            //需传递的数据
      action="no">
      <el-button size="small" type="primary">选取文件</el-button>
    </el-upload>
</el-form-item>
<el-form-item label="">
    <el-button type="primary" @click="submitUpload">导入</el-button>
    <el-button type="primary" @click="cancel">取消</el-button>
</el-form-item>
 

 submitUpload() { 
    this.$refs.upload.submit()   //	手动上传文件列表
 },
 import(val) {
    const fd = new FormData()
    fd.append('data', JSON.stringify(val.data))
    fd.append('file', val.file)
    import(fd).then(res => {     //向后请求
       console.log('导入成功')
    })
  }

 后端代码如下

@PostMapping("import")
public void import(@RequestParam("file") MultipartFile file, @RequestParam("data") String json) {
   try {
        Entity entity= JSON.parseObject(json, Entity .class);
        //操作文件
   } catch (Exception e) {
        e.printStackTrace();
   }
        
 }

2、自动上传

<el-form ref="form" :model="form" :rules="rules" size="small">
    <el-upload
      :action="uploadApi"
      :headers="headers"
      :on-success="handleSuccess"
      :on-error="handleError"
      class="upload-demo"
      drag>
      <i class="el-icon-upload" />
      <div class="el-upload__text">
        将文件拖到此处,或
        <em>点击上传</em>
      </div>
      </el-upload>
</el-form>

export default {
  data() {
    return {
     uploadApi: process.env.VUE_APP_BASE_API+ '/upload'
    }
  },
methods: {
    cancel() {
      this.resetForm()
    },
    handleSuccess(response, file, fileList) {
      this.cancel()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    }
  }
}

后端代码如下

@PostMapping(value = "/upload")
public ResponseEntity<Object> upload(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{

    //解析操作文件
}

3、导出

  export default {
    name: 'Cadata',
    inject: ['reload'],
    data() {
      return {},
      }
    },
    methods: {

    export() {
     data.exportData(data).then(res => {
       if (res != null) {
       this.downloadFile(res, this.caname, '.p12')
                    // this.reload();
          }
       }).catch(() => {
          this.loading = false
       })
    },
    
    downloadFile(obj, name, suffix) {
       const url = window.URL.createObjectURL(new Blob([obj], {type: 'application/x-pkcs12'}))
       const link = document.createElement('a')
       link.style.display = 'none'
       link.href = url
       const fileName = name + suffix
       link.setAttribute('download', fileName)
       document.body.appendChild(link)
       link.click()
       document.body.removeChild(link)
    }
  }
}



js:

   export function exportData(data) {
      return request({
         url: 'api/exportData',
         method: 'post',
         data: data,
         responseType: 'blob',
         headers: {
           'Content-Type': 'application/x-pkcs12' // 请求的数据类型为form data格式
         }
     })

后台代码

 @PostMapping("exportData")
    public void exportData(@RequestBody Entity entity, HttpServletResponse res, HttpServletRequest req) {
      
        try {

            byte[] bytes ;  //获取要导出数据
            String encoding = req.getCharacterEncoding();
            if (StringUtils.isEmpty(encoding)) {
                encoding = "UTF-8";
            }
            req.setCharacterEncoding(encoding);
            res.setContentType("application/octet-stream");
            res.setHeader("Content-disposition", "attachment; filename=\"" + StringTools.stripFilename(caname + ".p12") + "\"");
            log.info("======导出结束======");

        } catch (Exception e) {
            log.error("error:" + e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
//                    if (deleteOnExit) {
//                        file.deleteOnExit();
//                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

get请求方式

1、导出

 down(data) {
    cafunctions.download(data.caid).then(res => {  
      this.downPemFile(res, name, 'pem')   //和导出方法一样

    })
 }


js:
    export function download(caid) {
      return request({
        url: 'api/certificatedata/downloadJks?caid=' + caid ,
        method: 'get',
        responseType: 'blob'
  })
}

后台代码如下

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

 

 

 

Logo

前往低代码交流专区

更多推荐