Recently, I encountered some problems when writing the file on the page through AJAX requesting server to download files. Most of the information and introductions found online are not sound and systemic. In the end, I found a solution myself. I will write a brief draft first and then add it in detail later.
Table 1: Various situations when the front-end requests the back-end to download files
Request method | Request method | Response results |
---|---|---|
GET | Page jump | The URL corresponding to the file |
POST | AJAX | Binary stream of files |
First, you need to declare the file type returned by the corresponding request in src/service/:
import request from '@/utils/request'; export async function Download(params = {}) { return request(`/api/download`, { method: 'POST', // GET / POST are OK data: params, responseType : 'blob', // It must be noted that the return of binary stream is }); }
Then write the business logic for the relevant request processing in the corresponding model:
import { message } from 'antd'; import { Download } from '@/services/api'; export default { namespace: 'download', state: {}, effects: { *download({ payload, callback }, { call }){ const response = yield call(Download, payload); if (response instanceof Blob) { if (callback && typeof callback === 'function') { callback(response); } } else { ('Some error messages...', 5); } } }, reducers: {}, }
Finally, write the business logic related to the page component, click the download button, and distribute the download action to the model:
import React, { Component } from 'react'; import { Button } from 'antd'; import { connect } from 'dva'; @connect(({ download, loading }) => ({ download, loading: ['download/download'], })) class ExampleDownloadPage extends Component { handleDownloadClick = e => { (); const { dispatch } = ; const fileName = ''; dispatch({ type: 'download/download', payload: {}, //Fill in parameters according to actual situation callback: blob => { if () { (blob, fileName); } else { const link = ('a'); const evt = ('MouseEvents'); = 'none'; = (blob); = fileName; (link); // This writing method is compatible with Firefox browser ('click', false, false); (evt); (link); } } }); } render(){ const { loading } = ; return <Button loading={loading} icon="download" onClick={} > download </Button>; } }
The work is done! ~~
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.