快递下载csv附件响应不起作用

时间:2019-12-14 22:44:17

标签: reactjs express mongoose download stream

您好,我试图从包含下载附件的帖子要求中发送响应。我得到正确的答复,但没有弹出下载或另存为。我检查并正确设置标题。我正在使用express,mongodb,mongoose和nextjs。该控制器功能从请求和查询集合中获取开始和结束日期。 cvsReadStream流转换为csv表格式,然后通过管道传递给响应。

控制器:

exports.postExportApplications = (req, res, next) => {
  const startDate = new Date(req.body.startDate)
  const endDate = new Date(req.body.endDate)
  const fileName = `${moment(startDate).format('MM-DD-YYYY')}-${moment(endDate).format('MM-DD-YYYY')}-Applications.csv`
  if (req.session.user) {
    res.attachment(fileName)
    return Application.find({ dateTime: { $gte: startDate, $lte: endDate } } )
      .sort({ dateTime: 1 })
      .then(applications => {
        Application.csvReadStream(applications)
          .pipe(res)
      })
  } else {
    return res.sendStatus(401);
  }
}

响应头:

Connection: keep-alive
Content-Disposition: attachment; filename="12-13-1994-12-20-2020-Applications.csv"
Content-Type: text/csv; charset=utf-8
Date: Sat, 14 Dec 2019 22:42:10 GMT
Strict-Transport-Security: max-age=15552000; includeSubDomains
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block

表单组件:

import React, { useState } from 'react'
import InputMask from 'react-input-mask'

const ExportAppsForm = (props) => {

  const defaultData = {
    startDate: { value: '', error: false },
    endDate: { value: '', error: false },
  }

  const [form, setform] = useState(defaultData)

  const handleChange = (event) => {
    const target = event.target
    const name = target.name
    setform({
        ...form,
        [name]: target.value
    })
  }

  const submitform = () => {
    props.handleFormSubmit({...form})
  }

  return (
    <form encType="multipart/form-data">
      <div className="form-row">
        <div className="form-group col-md-4">
          <label htmlFor="year">Start Date:</label>
          <InputMask 
            mask="99/99/9999"
            onChange={handleChange}
            value={form.startDate}
            name="startDate"
            className="form-control"
            id="startDate"
            aria-describedby="emailHelp"
            />
        </div>
        <div className="form-group col-md-4">
          <label htmlFor="make">End Date:</label>
          <InputMask 
            mask="99/99/9999"
            onChange={handleChange}
            value={form.endDate}
            name="endDate"
            className="form-control"
            id="endDate"
            />
        </div>
      </div>
      <button onClick={submitform} type="button" className="btn btn-primary">Export Now!</button>
    </form>
  )
}

export default ExportAppsForm;

axios发布请求:

export const postExportApplications = (query) => {
  return axios.post(`${BASE_URL}/export`, query).then(res => res.data)
}

1 个答案:

答案 0 :(得分:0)

似乎您只是在查询以csv格式获取数据,所以HTTP GET方法最适合这种情况,因为您没有修改任何资源 参见:http://restcookbook.com/HTTP%20Methods/idempotency/

首先,您必须更改控制器以接受该查询作为查询参数,并使用axios发出GET请求,如下所示

export const getCsv = (params) => {
  axios({
      method: 'GET',
      url: '[YOUR_URL_HERE]'
      params,            
      responseType: 'arraybuffer',
      headers: {
         'Accept': 'text/csv'
      }
  }).then(response => {
     if(response.status === 200 && response){
        return response.data;
     }
  }).catch(error => console.log(error));         
}

要在班级组件中下载csv文件 使用名为file-saver的包

npm i file-saver

并按如下所示导入包

import { saveAs } from 'file-saver';

然后,您可以在组件中为onClick处理程序使用getCSv函数

funcion onHandleDownload(query) => {
   getCsv(query).then(data => {
      const blob = new Blob([data], {
           type: 'text.csv',
       });
       saveAs(blob, 'csv_name.csv')
   })
}