使用了 el-upload 的插件,但是一直都是报 404 ,在这个过程中,请注意您使用的 request header 中的 content-type 不同的类型需要的 NodeJS 的 request 解析方式不一样。在 Node 服务端接到用户的数据之后,就需要使用 fs 模块把图片解析成可以保存的文件流,存入磁盘中或者调用后台接口保存。调试了一个小时之后成功通过。把代码留下来,方便日后进行查询。
Vue 层
-------------------------------------
<el-upload class="avatar-uploader" accept="image/jpeg" action="agency/uploadPicForAgency" :data="{agencyId:'1',picFlag:'1'}" :multiple="false" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeBackgroundAvatarUpload">
<img v-if="backgroundUrl" :src="backgroundUrl" width="100%" height="100%" class="avatar">
<i v-else="" class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
express 层
-----------------------------------
/**
* @api {post} agency/uploadPicForAgency 代理商图片上传接口,返回图片存入服务器的URL
* @apiName agency/uploadPicForAgency
* @apiGroup agency
*
* @apiParam {FileObject} imgInfo 图片文件对象
* @apiParam {String} agencyId 代理商ID
* @apiParam {String} picFlag 图片标记(1-登录页logo图,2-登录页背景图,3-内容页logo图)
*
* @apiParamExample {type} Request-Example:
* 传统的FORM表单提交
* Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryzJ4Ys0x4h70Z8heR
*
* ------WebKitFormBoundaryzJ4Ys0x4h70Z8heR
Content-Disposition: form-data; name="agencyId"
000192
------WebKitFormBoundaryzJ4Ys0x4h70Z8heR
Content-Disposition: form-data; name="picFlag"
1
------WebKitFormBoundaryzJ4Ys0x4h70Z8heR
Content-Disposition: form-data; name="file"; filename="Intel-logo.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryzJ4Ys0x4h70Z8heR--
*
* @apiSuccessExample {Object} Success-Response:
* {
* message: ""
* success: true
* data: {
* imageStr: "/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAAXA.............."
uploadPath: "agency/2019/05/54e4c76df1db41bbbca80c9a7ef16c5f.jpg"
}
* }
*/
router.post('/uploadPicForAgency', function (req, res, next) {
const methodName = 'MAgencyPlatformDataAPI.uploadPicForAgency';
var form = new formidable.IncomingForm();
form.encoding = 'utf-8'; //设置编辑
form.keepExtensions = true; //保留后缀
form.maxFieldsSize = 2 * 1024 * 1024; //设置单文件大小限制
form.parse(req, function (err, fields, files) {
const agencyId = fields.agencyId;
const picFlag = fields.picFlag;
var imageBuf = fs.readFileSync(files.file.path);
var imagebase = imageBuf.toString("base64");
var imgInfo = {
imgName: files.file.name,
imgStr: imagebase,
}
util.JSONRPC(methodName, [imgInfo,agencyId,picFlag], function (data) {
res.json({
success: true,
data: {
uploadPath: data,
imageStr: imagebase
},
message: ''
})
}, res);
})
});