Pure Node.js文件上载(多部分POST)而不使用框架

bat*_*ksu 7 node.js

第三方库"node-formidable"和"express"具有处理多部分POST请求的能力(例如,使用文件上载表单),但我不想使用任何第三方代码.如何在Node.js上使用纯JavaScript进行文件上载过程?

在这方面资源很少.如何才能做到这一点?谢谢,爱是.

J.N*_*nen 7

Just to clarify because it seems some people are angry that the other answer didn't help much: There is no simple way of doing this without relying on a library doing it for you.

First, here's an answer to another question trying to clarify what happens on a POST file upload: /sf/answers/606251831/

To summarize, to parse such an upload, you'll first need to check for a Content-Type header containing "multipart/form-data" and, if one exists, read the boundary attribute within the header.

After this, the content comes in multiple parts, each starting with the boundary string, including some additional headers and then the data itself after a blank line. The browser can select the boundary string pretty freely as long as such byte sequence doesn't exist in the uploaded data (see the spec at http://tools.ietf.org/html/rfc1867 for details). You can read in the data by registering a callback function for the request object's data event: request.on('data', callback);

For example, with boundary "QweRTy", an upload might look something like this:

POST /upload HTTP/1.1
(some standard HTTP headers)
Content-Type: multipart/form-data; boundary=QweRTy

--QweRTy
Content-Disposition: form-data; name="upload"; filename="my_file.txt"
Content-Type: text/plain

(The contents of the file)
--QweRTy--
Run Code Online (Sandbox Code Playgroud)

Note how after the initial headers two dashes are added to the beginning of each boundary string and two dashes are added to the end of the last one.

Now, what makes this challenging is that you might need to read the incoming data (within the callback function mentioned above) in several chunks, and there are no guarantees that the boundary will be contained within one chunk. So you'll either need to buffer all the data (not necessarily a good idea) or implement a state machine parser that goes through the data byte by byte. This is actually exactly what the formidable library is doing.

So after having similar considerations, what I personally decided to do is to use the library. Re-implementing such a parser is pretty error-prone and in my opinion not worth the effort. But if you really want to avoid any libraries, checking the code of formidable might be a good start.


Sha*_* Xu 0

我认为如果你不想太多使用任何模块,你需要自己解析表单。上传文件时,表单将采用multipart/form-dataformat 格式,这意味着您的请求内容将除以浏览器随机生成的字符串。你需要在表单的开头读取这个字符串,尝试加载数据并找到这个字符串,然后一一解析它们。

有关multipart/form-data您的更多信息,请参阅http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

我认为最好的解决方案是使用formidable. 我认为它可以处理不同的场景并且工作得很好。