2014-08-23
Starting today to learn node. js, when writing a file upload function, call the Fs.renamesync method error
The error code is as follows:
1 functionUpload (response,request) {2Console.log ("Upload called");3 varform =NewFormidable. Incomingform ();4Console.log ("About to parse");5Form.parse (Request,function(Error, fields, files) {6Console.log ("Parsing done");7 Fs.renamesync (Files.upload.path, "./tmp/test.jpg"); 8Response.writehead ($, {"Content-type": "Text/html"});9Response.Write ("Received image:<br/>");TenResponse.Write ("); One Response.End (); A }); -}
After a rough analysis, it is expected that there will be permissions issues for moving or manipulating files across disk partitions .
The following two solutions are available:
Method One:
The Createreadstream, Createwritesream and Unlinksync methods of FS are mainly utilized.
The specific code is as follows:
1 functionUpload (response,request) {2Console.log ("Upload called");3 varform =NewFormidable. Incomingform ();4Console.log ("About to parse");5Form.parse (Request,function(Error, fields, files) {6Console.log ("Parsing done");
7 //Fs.renamesync (Files.upload.path, "./tmp/test.jpg");8 var readstream=Fs.createreadstream (files.upload.path); 9 var writestream=fs.createwritestream ("./tmp/test.jpg"); Ten readstream.pipe (writestream); One readstream.on (' End ',function() { fs.unlinksync (Files). Upload.path); );
-Response.writehead ($, {"Content-type": "Text/html"}); theResponse.Write ("Received image:<br/>"); -Response.Write ("); - Response.End (); - }); +}
PS: I use the node version is 0.10.69, if you are using a version below 0.6, you can use the Util.pump
The code simply changes the Readstream.on in the above code to: (Note the introduction of the Util module)
function () { fs.unlinksync (' Files.upload.path ');});
Method Two:
This is a lot simpler.
Add a form.uploaddir= ' tmp ' (write a temporary path)
1 functionUpload (response,request) {2Console.log ("Upload called");3 varform =NewFormidable. Incomingform ();4 form.uploaddir= ' tmp '; 5 6Console.log ("About to parse");7Form.parse (Request,function(Error, fields, files) {8Console.log ("Parsing done");9Fs.renamesync (Files.upload.path, "./tmp/test.jpg");TenResponse.writehead ($, {"Content-type": "Text/html"}); OneResponse.Write ("Received image:<br/>"); AResponse.Write ("); - Response.End (); - }); the } -
Solve the problem, you can be happy to continue my node study, feel the road is still very long
PS: attached two posts about node file upload, personally feel very good, the source is Cnode
- Nodejs-post File Upload principle detailed
- Node-formidable detailed
Fixed a problem with node. js calling Fs.renamesync error (Error:exdev, Cross-device link not permitted)