简体   繁体   English

使用sails.js在nodejs服务器中上传文件

[英]upload a file in nodejs server with sails.js

I created a server using sails.js on node with an end-point to upload files on the server by following the example in this page . 我通过遵循此页面中的示例,在节点上使用sails.js创建了一个具有端点的服务器,以在服务器上上传文件。

Here the complete code: 这里是完整的代码:

req.file('file').upload({
  maxBytes: 10000000,
  dirname: './my-dir'
}, function whenDone (err, uploadedFiles) {
  var fs = require('fs');

  if (err) {
    return res.negotiate(err);
  }

  // If no files were uploaded, respond with an error.
  if (uploadedFiles.length === 0){
    return res.badRequest('No file was uploaded');
  }

  console.log('file exists:', fs.existsSync(uploadedFiles[0].fd));

  var path = uploadedFiles[0].fd;
  var tmpFileName = /[^/]*$/.exec(path)[0];
  var url = '/my-dir/'+tmpFileName;

  return res.send(url);
});

The console.log line was added just to be sure that the file exists when the function whenDone is called (and the file exists already for every single call). 添加console.log行只是为了确保在调用函数whenDone时文件存在(并且每次调用已存在该文件)。

The problem is that on client-side: when the page sends a file to this end-point and receives the response from the server, it try to send another request to the same uploaded file (generally an image) and it receive a 404. 问题是在客户端上:当页面将文件发送到此端点并从服务器接收响应时,它尝试将另一个请求发送到相同的上载文件(通常是图像),并且收到404。

With the console.log I checked that the file exists and I'm sure that the url is correct for if I try to access the file with the url the server returns the file, and also if I add a setTimeout on client-side code works for 90% of times (it means that it's a timing issue). 使用console.log我检查了该文件是否存在,并且我确定该URL是否正确,如果我尝试使用该URL访问该文件,服务器将返回该文件,以及是否在客户端代码上添加了setTimeout工作90%的时间(这意味着时间问题)。

Is there some sails.js event fired when the file is not just loaded but also ready to be sent to the client? 当文件不仅被加载而且还准备好发送给客户端时,是否会触发一些sails.js事件?

Thanks in advance. 提前致谢。

Static assets (uploaded files in your case) are fetched from the .tmp directory in your project root. 从项目根目录的.tmp目录中提取静态资产(在您的情况下为上传的文件)。 When sails is lifted, .tmp is cleaned up and populated with all assets (from your assets directory). 抬起帆时, .tmp会清理并填充所有资产(来自您的assets目录)。 However, when a new file is added, it isn't copied to .tmp instantly, leading to the 404 s you mentioned. 但是,添加新文件后,该文件不会立即复制到.tmp ,导致您提到的404 s。

To get over this, you can copy the file to the .tmp directory right after the upload finishes, before sending the response to the client. 为了解决这个问题,您可以在上传完成后立即将文件复制到.tmp目录,然后再将响应发送给客户端。

This thread can help you with the copying. 线程可以帮助您进行复制。

A better way would be to upload directly to a CDN or S3. 更好的方法是直接上传到CDN或S3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM