跳到主要内容

Axios 下载

· 阅读需 4 分钟
素明诚
Full stack development

get请求,下载为例。一般项目中的axios都是经过封装的,所以你需要关注有没有添加responseType这是关键。

export const exportQuotation = (id: string | number) => {
return request({
responseType: 'blob', // 二进制流
url: '/dcomsp-sales/excelExport/v1/export',
method: 'get',
params: {
id,
},
})
}

通用下载函数

/**
* 下载文件
* @param fileData
* @param fileType
* @param fileName
*/
export function downloadFile(
fileData: any,
fileType: string,
fileName: string
): boolean {
let blob: Blob
let success = true // 假设初始状态为成功

// 创建 Blob 对象
try {
if (fileData instanceof Blob) {
blob = fileData
} else {
blob = new Blob([fileData], { type: fileType })
}
} catch (error) {
console.error('Error creating the Blob:', error)
return false
}

const a = document.createElement('a')
const url = window.URL.createObjectURL(blob)

// 下载后释放URL资源和清理逻辑
const cleanup = () => {
window.URL.revokeObjectURL(url)
document.body.removeChild(a)
}

try {
// 创建一个隐藏的可点击的a标签,然后模拟点击进行下载
a.href = url
a.download = fileName
a.style.display = 'none'
document.body.appendChild(a)
a.click()
} catch (error) {
console.error('Error triggering the download:', error)
success = false // 下载失败时,设置 success 为 false
} finally {
// 使用setTimeout确保清理逻辑在下载触发后立即执行
setTimeout(cleanup, 0)
}

return success // 返回下载的状态
}

使用,通过id进行下载

const download = async (id: string | number) => {
// exportQuotation 是我的接口,拿到流数据传递给下载函数
const exportData = await exportQuotation(id)
// 创建下载
const res = downloadFile(
exportData.data,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
`${id}-${Date.now()}.xlsx`
)
if (res) {
ElMessage.success('下载成功')
} else {
ElMessage.error('下载失败')
}
}

常用下载格式

后缀类型格式
aacAAC audioaudio/aac
.abwAbiWord documentapplication/x-abiword
.arcArchive document (multiple files embedded)application/x-freearc
.aviAVI: Audio Video Interleavevideo/x-msvideo
.azwAmazon Kindle eBook formatapplication/vnd.amazon.ebook
.binAny kind of binary dataapplication/octet-stream
.bmpWindows OS/2 Bitmap Graphicsimage/bmp
.bzBZip archiveapplication/x-bzip
.bz2BZip2 archiveapplication/x-bzip2
.cshC-Shell scriptapplication/x-csh
.cssCascading Style Sheets (CSS)text/css
.csvComma-separated values (CSV)text/csv
.docMicrosoft Wordapplication/msword
.docxMicrosoft Word (OpenXML)application/vnd.openxmlformats-officedocument.wordprocessingml.document
.eotMS Embedded OpenType fontsapplication/vnd.ms-fontobject
.epubElectronic publication (EPUB)application/epub+zip
.gifGraphics Interchange Format (GIF)image/gif
.htm .htmlHyperText Markup Language (HTML)text/html
.icoIcon formatimage/vnd.microsoft.icon
.icsiCalendar formattext/calendar
.jarJava Archive (JAR)application/java-archive
.jpeg.jpgJPEG imagesimage/jpeg
.jsJavaScripttext/javascript
.jsonJSON formatapplication/json
.jsonldJSON-LD formatapplication/ld+json
.mid.midiMusical Instrument Digital Interface (MIDI)audio/midi audio/x-midi
.mjsJavaScript moduletext/javascript
.mp3MP3 audioaudio/mpeg
.mpegMPEG Videovideo/mpeg
.mpkgApple Installer Packageapplication/vnd.apple.installer+xml
.odpOpenDocument presentation documentapplication/vnd.oasis.opendocument.presentation
.odsOpenDocument spreadsheet documentapplication/vnd.oasis.opendocument.spreadsheet
.odtOpenDocument text documentapplication/vnd.oasis.opendocument.text
.ogaOGG audioaudio/ogg
.ogvOGG videovideo/ogg
.ogxOGGapplication/ogg
.otfOpenType fontfont/otf
.pngPortable Network Graphicsimage/png
.pdfAdobe Portable Document Format (PDF)application/pdf
.pptMicrosoft PowerPointapplication/vnd.ms-powerpoint
.pptxMicrosoft PowerPoint (OpenXML)application/vnd.openxmlformats-officedocument.presentationml.presentation
.rarRAR archiveapplication/x-rar-compressed
.rtfRich Text Format (RTF)application/rtf
.shBourne shell scriptapplication/x-sh
.svgScalable Vector Graphics (SVG)image/svg+xml
.swfSmall web format (SWF) or Adobe Flash documentapplication/x-shockwave-flash
.tarTape Archive (TAR)application/x-tar
.tif .tiffTagged Image File Format (TIFF)image/tiff
.ttfTrueType Fontfont/ttf
.txtText, (generally ASCII or ISO 8859-n)text/plain
.vsdMicrosoft Visioapplication/vnd.visio
.wavWaveform Audio Formataudio/wav
.webaWEBM audioaudio/webm
.webmWEBM videovideo/webm
.webpWEBP imageimage/webp
.woffWeb Open Font Format (WOFF)font/woff
.woff2Web Open Font Format (WOFF)font/woff2
.xhtmlXHTMLapplication/xhtml+xml
.xlsMicrosoft Excelapplication/vnd.ms-excel
.xlsxMicrosoft Excel (OpenXML)application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xmlXMLapplication/xml 代码对普通用户来说不可读 (RFC 3023, section 3)text/xml 代码对普通用户来说可读 (RFC 3023, section 3)
.xulXULapplication/vnd.mozilla.xul+xml
.zipZIP archiveapplication/zip
.3gp3GPP audio/video containervideo/3gppaudio/3gpp(若不含视频)
.3g23GPP2 audio/video containervideo/3gpp2audio/3gpp2(若不含视频)
.7z7-zip archiveapplication/x-7z-compressed