6. 安装mysql
npm install mysql
npm install @types/mysql -D
7. 新建mysql配置文件以及连接mysql
新建mysql.config.ts文件

model目录下新建index.ts连接mysql,如果image表不存在则创建


最后入口server.js别忘了引入model

image表已成功创建!

8. 使用jade模板引擎新建upload.jade文件充当前端页面
这块不是重点,就是用express自带的jade模板写个文件上传的html页面
文件上传将会调用后端接口:http://localhost:3000/api/file_upload
在routes/index中追加路由,指向模板界面

upload.jade内容如下

页面效果是这样的:

9. 编写文件上传所需的api/file_upload接口
新建路由文件 route/api.ts(解耦嘛...)

routes/api.ts中引入controller/api.ts文件

controller/api.ts内容如下(我们将文件上传和写入mysql的方法都封装了一下)

文件上传方法:

这里用到了formidable包(这个包专门处理post上传文件的,这里不做具体描述),自然少不了安装包和包的声明文件
npm install formidable
npm install @types/formidable -D
官方文档内容如下:

上传记录写入mysql方法如下:

10. 测试成功!将打包后的文件放入服务器中即可!

npm run build (tsc && node handle-public.js)打包之后的结果:
public和views等静态资源被我们通过shelljs复制到dist文件夹下了

网友评论