简体   繁体   中英

Local file download is corrupted

I am trying to download a file to my windows pc using nodejs

I tried the following code. the problem is the file which i download from nodejs is 185kb and the actual original file size is 113kb(found by directly downloading from browser)

request = require('request');

function download(url, dest, cb){
  request.head(url, function(err, res, body){
    request(url).pipe(fs.createWriteStream(dest)).on('close', function(){
        cb();
    });
  });
};

I also tried downloading the file using a different code

function download(url, dest, cb) {
    var file = fs.createWriteStream(dest);
    var request = https.get(url, function (response) {
        response.pipe(file);
        file.on('finish', function () {
            file.close(cb);
            file.end();
        });
    });
}

But the same bug happened

The problem is i am trying to open that file in photoshop, but it fails, saying the file is corrupted, please help

This code (using the built-in https module) should work correctly. The stream will close automatically, there's no need to close it, the autoClose parameter defaults to true when creating a write file stream.

See docs at: fs.createWriteStream .

If the file is still too large it is likely that you are not using the direct image link, try selecting "View image" / "Open image in new tab" etc. in your browser and using that link instead.

const https = require("https");
const fs = require("fs");

const url = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/1024px-FullMoon2010.jpg";
const fileStream = fs.createWriteStream("test.jpg");
https.get(url, response => {
    response.pipe(fileStream);
});

You can also use the request library:

const request = require("request");
const fs = require("fs");

const url = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/1024px-FullMoon2010.jpg";
const fileStream = fs.createWriteStream("request-test.jpg");
const req = request(url);

req.on("response",  response => {
    response.pipe(fileStream);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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