# 2. uni-app使用Node+Koa2接收上传的文件

通过其它客户端上传(h5,小程序等),接收方法一致

使用koa接收时,我们需安装一个中间件**koa-body**

## 安装所需中间件

```
npm install --save koa-body
```

## 配置koa-body

```javascript
//...code
const Koa = require('koa');

const koaBody = require("koa-body");

const app = new Koa();
app.use(koaBody({
    multipart: true,
    strict: false,//解析所有请求
    formidable: {
         maxFileSize: 200 * 1024 * 1024//文件大小限制
    }
}))
//...code
```

## uni-app中上传文件请求

```javascript
methods:{
    /**
    * 上传文件
    * @param {String} filePath 文件所在临时路径
    */
    uploadFile:function(filePath){
        uni.uploadFile({
            url:`${this.baseUrl}/file/upload`,
            formData:{
                account:"123456",
                typeName:"水果"
            },
            filePath:filePath,
            name:"file",
            success: (res) => {
                console.log(res.data);
                // {code:200,filename:"文件名.xx"}
            }
        })
    }
}
```

### 上传函数提示

* 上传参数filePath 是uni.chooseImage API的成功回调参数tempPath(Array)中的内容

## 接收文件代码

```javascript
const fs = require("fs");

/**
 * 处理文件上传方法
 * @requestParam {Number} account 账号
 * @requestParam {String}  typeName 分类名称
 */
const fn_uploadFile = async (ctx, next) => {
    // 获取body中携带的参数
    const { account, typeName } = ctx.request.body;
    // account:123456
    // typeName:水果

    // 通过ctx.request.files.file方法获取上传的文件对象

    // 获取文件名称与文件所在路径
    const { name: filename, path } = ctx.request.files.file;

    // 创建文件输入流
    const fileReader = fs.createReadStream(path);

    // 文件将要的存放文件夹路径
    const fileDir = `${__dirname}/../../../upload-static/images/${account}/${typeName}`;

    // 判断目录是否存在,目录不存在则创建
    if (!fs.existsSync(fileDir)) {
        try {
            fs.mkdirSync(fileDir);
        } catch (e) {
            console.error(e);
        }
    }

    // 保存文件的最终路径 (文件夹路径+文件名)
    const filepath = `${fileDir}/${filename}`;

    // 创建文件输出流
    const fileWriter = fs.createWriteStream(filepath);

    // 写入文件数据
    fileReader.pipe(fileWriter);

    // 至此文件已上传完成

    // 向客户端返回的内容
    ctx.response.body={
        code: 200,
        filename
    };
}

module.exports = {
    "POST /api/file/upload": fn_uploadFile
}
```

## 参考资源

> [koa2](https://github.com/koajs/koa)\
> &#x20;[koa-body](https://github.com/dlau/koa-body)\
> &#x20;[node-formidable](https://github.com/node-formidable/node-formidable)\
> &#x20;[uni-app API文档](https://uniapp.dcloud.io/api/README)
>
> [uni-app 文件上传API文档](https://uniapp.dcloud.io/api/request/network-file?id=uploadfile)\
> &#x20;[uni-app 图片选择API文档](https://uniapp.dcloud.io/api/media/image?id=chooseimage)<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sugar-at.gitbook.io/blog-article/node/p2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
