nestjs 文件上傳

文件上傳需要使用 攔截器 UseInterceptors 在'@nestjs/common'包內(nèi)

攔截器功能參考:https://docs.nestjs.cn/7/interceptors

單文件上傳

所需依賴有FileInterceptor,UploadedFile

FileInterceptor 是攔截器負(fù)責(zé)處理請(qǐng)求接口后的文件 再使用UploadedFile 進(jìn)行接受

    import {  UploadedFile, UseInterceptors ,Body } from '@nestjs/common';
    import {  FileInterceptor } from '@nestjs/platform-express';

    @Post("upload/single")
    // "file" 表示 上傳文件的鍵名
    @UseInterceptors(FileInterceptor("file"))
    upload(@UploadedFile() file, @Body() body) {
        //body為form/data中的其他非文件參數(shù)
        console.log(file, body);
        return "上傳成功"
    }
    // 注意!如果當(dāng)前參數(shù)名沒有"file"鍵將自動(dòng)報(bào)錯(cuò)為400

多文件上傳

所需依賴有FilesInterceptor,UploadedFiles

基本操作與單文件上傳一致 但注意依賴名不同,多文件上傳有復(fù)數(shù)s

    import {  UploadedFiles, UseInterceptors ,Body } from '@nestjs/common';
    import {  FilesInterceptor } from '@nestjs/platform-express';

    @Post("upload/multiple")
    @UseInterceptors(FilesInterceptor("files"))
    uploadMultiple(@UploadedFiles() files, @Body() body) {
        // files 變成數(shù)組,可以傳遞多個(gè)文件 
        console.log(files, body);
        return "上傳成功"
    }

多文件上傳自定義多個(gè)鍵名

所需依賴有FileFieldsInterceptor,UploadedFiles

與上述操作基本不變 僅攔截方法變更,需要傳入?yún)?shù)名數(shù)組

    import {  UploadedFiles, UseInterceptors ,Body } from '@nestjs/common';
    import {  FileFieldsInterceptor } from '@nestjs/platform-express';

    @Post("upload/multipleKey")
    @UseInterceptors(FileFieldsInterceptor([
        //maxCount 為最大接受文件數(shù)量,這里為最多接收10個(gè)文件
        //不傳maxCount為無限制
        { name: "files", maxCount:10 },
        { name: "custom" }
    ]))
    uploadMultipleKey(@UploadedFiles() files, @Body() body) {
        // 這里files 將被改為對(duì)象 {files:[File],custom:[File]}
        console.log(files, body);
        return "上傳成功"
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容