-
Notifications
You must be signed in to change notification settings - Fork 1
Step1
techird edited this page Apr 6, 2016
·
1 revision
本步骤完整源码在 workflow/step-1 分支上,提交记录为
e027e28
现在,我们要先支持用户把图片上传到服务器上。
用户上传图片的流程图如下。
针对有文件上传的表单,表单的类型是 multipart/form-data
。我们需要解析这种类型的表单。当前项目选用了 multer 来作为解析工具。
首先,使用 NPM 安装 multer
:
npm init
npm install multer --save
紧接着,我们创建 handle/upload.js
来处理用户的上传请求:
// handle/upload.js
'use strict';
const multer = require("multer");
const printer = require("../lib/printer");
function upload(request, response) {
// initial a print util
const print = printer(request, response);
console.log("#0. Start processing upload...");
// use multer to handle the upload process
const processUpload = multer({
dest: "/data/uploads/project4.qcourse.net",
limits: {
fileSize: 3 * 1024 * 1024, // support max size at 3M
}
}).single('image');
processUpload(request, response, uploadToServer);
function uploadToServer(uploadError) {
if (uploadError) {
print({ uploadError });
return;
}
// check if any file uploaded
const file = request.file;
if (!file) {
print({ msg: "file is required" });
return;
}
console.log("#1. File uploaded to server:");
console.log(JSON.stringify(file, null, 4));
print({ file });
}
}
module.exports = upload;
这里使用到了一个本地上传目录,需要提前创建该目录。
mkdir -p /data/uploads/project4.qcourse.net
紧接着,在 server.js
添加对 /upload
的路由处理到 handle/upload.js
// server.js
app.use("/upload", require("./handle/upload"));
使用 SecureFX 同步源码到 CVM 后,PM2 会自动重启应用。
使用 Postman 提交报文,其中 image 字段包含图片。
在服务器上使用 pm2 logs
,可以看到日志有如下输出:
#0. Start processing upload...
#1. File uploaded to server:
{
"fieldname": "image",
"originalname": "qq.png",
"encoding": "7bit",
"mimetype": "image/png",
"destination": "/data/uploads/project4.qcourse.net",
"filename": "9da14693467cc7e9ccd9170351a4ef65",
"path": "/data/uploads/project4.qcourse.net/9da14693467cc7e9ccd9170351a4ef65",
"size": 59482
}
此时,查看上传目录,可以看到文件已经能成功地上传到服务器上。