kanasimi / wikiapi

JavaScript MediaWiki API for node.js
https://kanasimi.github.io/wikiapi/
BSD 3-Clause "New" or "Revised" License
48 stars 6 forks source link

Feature request: upload. #6

Closed hugolpz closed 3 years ago

hugolpz commented 3 years ago

Hello, You already got quite some useful, practical codes on the README.md, from wikipedias to wikidata, from GET to Replace.

Since the developments is active, I would suggest you the following new axe :

NodeJS syntaxe from :mw:API:Upload

// Step 4: POST request to upload a file directly
function upload(csrf_token) {
    var params_3 = {
        action: "upload",
        filename: "Sandboxfile1.jpg",                  // `data[i].filename` comes here
        ignorewarnings: "1",
        comment: "comment here",                    // `data[i].comment` comes here
        token: csrf_token,
        format: "json"
    };

    var file = {
        file: fs.createReadStream('My.jpg')         // `data[i].filepath` comes here
    };

    var formData = Object.assign( {}, params_3, file );

    request.post({ 
        url: url,               // API's root url such as "https://test.wikipedia.org/w/api.php";
        formData: formData 
    }, function (error, res, body) {
        body = JSON.parse(body);
        if (error) { return; }
        else if (body.upload.result === "Success"){
            console.log("File Uploaded :)");
        }
    });
}

Input parameters

Under consideration:

Some default parameters

Url or filepath

The difference between upload of local file or online file is minor and can be balanced via a conditional.

Example 1: Upload a local file directly Example 2: Upload file from URL
~~~ javascript // Step 4: POST request to upload a file directly function upload(csrf_token) { var params_3 = { action: "upload", filename: "Sandboxfile1.jpg", ignorewarnings: "1", token: csrf_token, format: "json" }; var file = { file: fs.createReadStream('My.jpg') }; var formData = Object.assign({}, params_3, file); request.post({ url: url, // API https://en.wikipedia.org/w/api.php formData: formData }, function(error, res, body) { body = JSON.parse(body); if (error) { return; } else if (body.upload.result === "Success") { console.log("File Uploaded :)"); } }); } ~~~ ~~~ javascript // Step 4: POST request to upload a file from a URL function editRequest(csrf_token) { var params_3 = { action: "upload", filename: "Test-ABCD.jpg", url: "https://farm9.staticflickr.com/8213/8300206113_374c017fc5.jpg", ignorewarnings: "1", token: csrf_token, format: "json" }; request.post({ url: url, // API https://en.wikipedia.org/w/api.php form: params_3 }, function(error, res, body) { body = JSON.parse(body); if (error) { return; } else if (body.upload.result === "Success") { console.log("File Uploaded :)"); } }); } ~~~

So a conditional and some minor fixes should be enough

Attached file

hugolpz commented 3 years ago

@kanasimi, thank for the quick integration. I'am trying to learn from your commits. :+1: