Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Post #174

Merged
merged 9 commits into from
Oct 14, 2015
Merged

Post #174

merged 9 commits into from
Oct 14, 2015

Conversation

viRingbells
Copy link
Contributor

新方案:

增加receive方法,通过receive方法将post的数据进行处理,并放到request.body中。

方案示例如下:

yield this.receive('json', 'urlencoded');
console.log(this.request.body);

POST的数据为:

curl -X POST 'localhost:3000/post' -d 'a=b%20c&d=e'

结果是:

{ a: 'b c', d: 'e' }

对于multipart/form-data的数据,则可以使用如下方法进行处理:

yield this.receive('multipart/form-data');
console.log(this.request.body);

获得的数据:

{ userfile: 
   { filename: 'haha.jpg',
     name: 'userfile',
     mime: 'image/jpeg',
     mimeType: 'image/jpeg',
     content: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 60 00 60 00 00 ff db 00 43 00 06 04 05 06 05 04 06 06 05 06 07 07 06 08 0a 10 0a 0a 09 09 0a 14 0e 0f 0c ... > } }

可见post的图片被转换成了buffer。

大多数情况下并不需要对post来的文件直接进行处理,而是进行保存,所以提供了一个saveAs参数,如:

yield this.receive('multipart/form-data', {
    saveAs: 'upload/{name}.jpg',
});

// alternative solution:
yield this.receive('multipart/form-data', {
    saveAs:  function (readable) { return 'upload/' + readable.name + '.jpg'; },
});

上述2个方案是等价的,不过必须保证readable下有name属性

这样上传之后,文件会被保存在对应的位置(通过管道的方式,因此不会占用过多的内存),这样得到的结果中不会有content而是被saveAs取代,saveAs中是保存的最终位置:

{ userfile: 
   { filename: 'haha.jpg',
     name: 'userfile',
     mime: 'image/jpeg',
     mimeType: 'image/jpeg',
     saveAs: '/Users/mbu-se-vc/haohao/projects/appPost/upload/userfile.jpg' } }

兼容的方式

已经和上一版进行兼容,选择对于urlencoded的数据,可以直接用this.request.body获取到数据。

viRingbells added a commit that referenced this pull request Oct 14, 2015
@viRingbells viRingbells merged commit 22658ec into master Oct 14, 2015
@viRingbells viRingbells deleted the post branch October 14, 2015 09:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant