bluebird 实现上传图片。发现了一个坑有没有更多的?重新贴了一下代码
功能上传图片,检查文件夹是否存在, **主要问题: express的req好像被赋予其他对象会丢失所以只能一层一层传下去 主要就是req 可以被form.parse 但是如果option.req = req 之后就报错了 ** 重修贴一下代码加一些注释。 **错误信息 POST /upload/meetingPhoto/561c700e7435be1a33cba428/10 - - ms - - not success [TypeError: Cannot read property ‘headers’ of undefined] ** 代码如下
path = require 'path'
formidable =require "formidable"
TMP_DIR = "public/tmp"
fs = require "fs"
Promise = require 'bluebird'
Promise.promisifyAll(fs)
meetingId = ''
index = ''
meetingPath = ''
MeetingPhoto = (myreq) ->
# 入口
meetingId = myreq.params.meetingId
index = myreq.params.index
meetingPath = path.join($WEBPATH,"/public/meetingPhoto/#{meetingId}")
return checkMeetingPath(meetingPath,myreq)
.then upload
.then renameAsync
checkMeetingPath = (meetingPath,myreq)->
# 检查文件夹是否存在或者被文件名占用
notExists = (exists)->
# 如果文件名不存在就创建
return fs.mkdirAsync(meetingPath)
isExists = (exists)->
# 如果文件名存在,检查是不是文件夹
return fs.statAsync(meetingPath)
.then isDirectory
isDirectory = (stats)->
# 检查是否文件夹
if stats.isDirectory()
# 是文件夹世界resole Promise
return Promise.resolve()
else
# 不是文件夹删文件并且调用创建
return fs.unlinkAsync(meetingPath)
.then notExists
success = ()->
# 整个过程都成功通知下一个promise 并且把req传过去
return Promise.resolve(myreq)
return fs.existsAsync(meetingPath)
.then notExists
.catch isExists
.then success
renameAsync = (orgPath)=>
# 上传结束,移动到指定目录
savePath = path.join meetingPath, "#{index}.jpg"
return fs.renameAsync orgPath, savePath
upload = (upReq)->
# 上传图片
# 修改成这样
# option = {req:upReq}
# 修改成这样
return new Promise (resolve,reject)->
form = new formidable.IncomingForm()
form.encoding = 'utf-8'
form.uploadDir = TMP_DIR
form.keepExtensions = true
# 修改成这样
#form.parse option.upReq, (err, fields, files) ->
# 修改成这样
# 被修改的部分
form.parse upReq, (err, fields, files) ->
# 被修改的部分
return reject {status:'fail',message:'上传失败,files不存在'} unless files?
return reject {status:'fail',message:'上传失败,err in form parse'} if err?
file = files['file']
return reject {status:'fail',message:'上传失败,file不存在'} unless file?
return resolve file.path
module.exports = MeetingPhoto
``` ![untitled1.png](//dn-cnode.qbox.me/Fli2HT4ZTDv9gg9-Ak2B103tJVrM) ![untitled2.png](//dn-cnode.qbox.me/FipGtr89ft5sfP0pBbJkSFNz3Q68)