文档上传(File Uploads)

TODO: Normalize/expand this section

例子

产生一个 api

首先,我们需要替 serving/storing 产生一个新的 api 文档。用 sails 命令行工具执行此动作。

  1. dude@littleDude:~/node/myApp$ sails generate api file
  2. debug: Generated a new controller `file` at api/controllers/FileController.js!
  3. debug: Generated a new model `File` at api/models/File.js!
  4. info: REST API generated @ http://localhost:1337/file
  5. info: and will be available the next time you run `sails lift`.
  6. dude@littleDude:~/node/myApp$

撰写控制器动作

让我们建立一个 index 动作来开始文档上传及 upload 动作来接收文档。

  1. // myApp/api/controllers/FileController.js
  2. module.exports = {
  3. index: function (req,res){
  4. res.writeHead(200, {'content-type': 'text/html'});
  5. res.end(
  6. '<form action="http://localhost:1337/file/upload" enctype="multipart/form-data" method="post">'+
  7. '<input type="text" name="title"><br>'+
  8. '<input type="file" name="avatar" multiple="multiple"><br>'+
  9. '<input type="submit" value="Upload">'+
  10. '</form>'
  11. )
  12. },
  13. upload: function (req, res) {
  14. req.file('avatar').upload(function (err, files) {
  15. if (err)
  16. return res.serverError(err);
  17. return res.json({
  18. message: files.length + ' file(s) uploaded successfully!',
  19. files: files
  20. });
  21. });
  22. }
  23. };

它们去哪了?

使用默认的 receiver,上传的文档会在 myApp/.tmp/uploads/ 目录。你可以在 upload 动作内做你想做的任何事情。

上传到自定义文件夹

在上面的例子中,我们可以将文档上传到 .tmp/uploads。那么我们该如何设置为自定义文件夹,例如 assets/images。我们可以通过增加选项到上传功能来实现这一目标,如下所示:

  1. var uploadPath = './assets/images';
  2. uploadFile.upload({ dirname: uploadPath },function onUploadComplete (err, files) {
  3. if (err)
  4. return res.serverError(err);
  5. return res.json({
  6. message: files.length + ' file(s) uploaded successfully!',
  7. path:uploadPath
  8. file:files
  9. });
  10. });

请查看 Skipper 文件取得更多资讯及其他可用的 receivers 清单!