endaaman.com

2015-11-23

Tips

koaで複数ファイルを一気にアップロードしたりするやつ

router.post '/:id/photos', auth, (next)->
    if not @request.is 'multipart/*'
        @status = 400
        return yield next

    album = yield Album.findById @params.id
    if not album
        @status = 404
        return yield next

    photos = []
    parts = parse this,
        autoFields: true
    while part = yield parts
        # There is transaction problem to fix
        hashStream = new PassStream
        writeSream = new PassStream
        part.pipe hashStream
        part.pipe writeSream


        photo = new Photo
            title: part.fieldname
            author: album.author
            album: album

        base = hashids.encodeHex photo._id
        ext = _.last part.filename.split '.'
        filename = path.join 'photos', "#{base}.#{ext}"
        filepath = path.join config.uploadDir, filename


        ret = [
            genHash hashStream
            cp writeSream, filepath
        ]
        part.resume()
        hash = (yield ret)[0]

        photo.file = filename
        photo.hash = hash

        try
            photo = yield photo.save()
        catch e
            console.log 'errored'
            yield fs.unlink path.join config.uploadDir, photo.file
            console.log 'remove: ', photo.file
            for p in photos
                yield Photo.findByIdAndRemove p._id
                yield fs.unlink path.join config.uploadDir, p.file
                console.log 'rollback and remove: ', p.title, p.file
            throw e
            return
        photos.push photo

    @body = photos
    yield next

トランザクションできてる複数ファイルを同時にアップロードするやつ。でもなんか微妙。


©2024 endaaman.com