2

I want "client.js" to read a file, and upload it to a certain folder via "server.js" using HTTP POST. When file size is small(1kb), it works. But when file size is bigger(maybe around 100kb), it doesen't work. There is no error, but the stored image is less in size than what it's supposed to be. I don't know why. please help.

1.client.js

var fs = require('fs');
var http =  require('http');

postData = null;

postData=fs.readFileSync("test.jpg")

if(postData!=null){

var options = {
  host: 'localhost',
  port: 10730,
  method: 'POST' 
};

var clientRequest = http.request(options);
clientRequest.end(postData);}

2.server.js

 var http =  require('http');
 var fs = require('fs');

 var server = http.createServer((req,res)=>{
   req.on('data', (chunk)=>{
   fs.writeFile('testcopy.jpg',chunk)})
   req.on('end', ()=>{
   console.log("end")
 })})
 server.listen(10730,'localhost');

Thank you in advance.

1
  • you can use busyboy to upload file, i am using it in my project and i handle images of large size in my application. Commented Jul 19, 2016 at 12:46

1 Answer 1

1

You can use multer, a middleware that handles multipart/form-data it automatically save the file for you and populates the req variable: req.file //access file info. It has a lot of functionalities that abstract this kind of work. You can define size of file, filter files and many other facilities, I know that multer is simple to use and works with express as a middleware but I think you can try this:

var http =  require('http');

var server = http.createServer((req,res)=>{
   upload(req, res, function (err) {
     if (err) {
        // An error occurred when uploading
        return
     }
     console.log('end')
      // Everything went fine
   })
})
server.listen(10730,'localhost');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for comment. I think I should use 'multer' as you said. But I just came to be curious about what is wrong with my code. Is there anyone who can explain the problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.