Multiple files are being posted to nodejs application using Express and bodyParser.
The number of files change in every request. It is required to get number of files posted at the server.
I have tried using
req.files.length
but it gives undefined. How can I know the number of files posted in a post request?
Also how to loop through each file?
Putting answer my self.
It should be iterated upon like this
for (x in files){
//code for handling each object in json.
}
You can get the length of and iterate a collection of files with the name of the <input>:
// example: <input type="file" name="images" multiple>
req.files.images.length;
req.files.images.forEach(function (file, i) {
// ...
});
You can find an example of this in the Connect repository: examples/upload.js
Related
I'm trying to port the following code from Ruby with the selenium-webdriver gem to Node.js with WebdriverIO:
#webdriver.navigate.to "https://imgur.com/upload"
element = #webdriver.find_element(:id, 'global-files-button')
element.send_keys("C:\\test\\image.png")
As you can see the code is very simple: navigate to a url, find the input, set the file path and it works as expected selecting the file for upload.
This is my ported version:
describe('User can upload', () => {
it('select file', () => {
browser.url("https://imgur.com/upload");
browser.waitForExist('#global-files-button');
$('#global-files-button').keys("C : \\ t e s t \\ i m a g e . p n g".split(" "));
});
});
Unfortunately this test doesn't set the path and I haven't been able to find a working example of uploading a file like this with wdio and the documentation has left me guessing. Any suggestions much appreciated.
I'm aware of both chooseFile and uploadFile but I'm working with a cloud platform to run my wdio tests and they don't seem to work reliably.
I've had trouble with this. From what I've researched it is not an issue with WebdriverIO or it's chooseFile() or uploadFile() methods. The root of the issue I believe comes down to an error in Selenium Webdriver being unable to handle the 'multiple' <input type='file' multiple> upload elements.
I fought this for a solid maybe 3 days before stumbling across this github issue:
https://github.com/SeleniumHQ/selenium-google-code-issue-archive/issues/2239
Long story short, because the HTML on imgur has the "multiple" property on it, your upload tests won't work correctly. WebdriverIO / Selenium just stops functioning from what I've noticed.
Note: I've been able to actually have my application upload a single file and add files to my system and application while testing an <input type='file' multiple>. The problem is however, that WebdriverIO and Selenium just stops. The tests end, without reporting any success or failure results.
If you go and test another <input type=file> element somewhere across the web that is NOT designated as a "multiple" upload input field you should be able to make the chooseFile() methods from WebdriverIO function correctly.
I hope this helps you and perhaps anyone else who's struggled with file uploads.
EDIT:
I've tried to make your example work, and I had success with "chooseFile()" and passing the "filepath" to it directly. Perhaps you're trying to send keyboard commands when you don't really have to? Do you have a direct file path to the image you're attempting to upload? Below is what i was able to use to successfully upload a file.
it('upload a file to imgur', function () {
browser.url("https://imgur.com/upload");
browser.waitForExist('#global-files-button');
browser.chooseFile('#global-files-button', '/insert/path/to/image.png')
})
// c:/test/image.png
var test1 = 'c:/test/image.png'
var path = test1.split('/').join('\\\\')
browser.addValue('[name="fileField"]', path )
or maybe this also work
// c:\test\image.png
var path = 'c:\\test\\image.png'
browser.addValue('[name="fileField"]', path )
or maybe this
// c:/test/image.png
var path = 'c:/test/image.png'
browser.addValue('[name="fileField"]', path )
Hi I need to automate a website using cucumberJS and webdriverIO. For that I need to Upload a file but the field is hidden. For Example :
<input type="file" id='uploadFile' style="display: none"'>
but webdriver is unable to identify the element on the UI.
Thanks in Advance...
In webdriverIO v5, files are uploaded to inputs of type="file" by calling .setValue() on them with the local file path as an argument. This doesn't seem to work for hidden inputs though, because .setValue() first calls .clearValue() which will throw Element could not be scrolled into view. To work around this, call .addValue() directly on the element:
input.addValue(filePath);
Relevant API docs: https://webdriver.io/docs/api/element/addValue.html
I got the solution for this Issue.Using webdriverIO we can execute javascript to change the style display from "none" to "block".
client.execute(function() {
document.getElementById("element_id").style.display="block";
},function(err) {
client.uploadFile(localPath[,callback])
if(err){
console.log("Error "+err);
}
});
then upload the file to the field and then change the display again to none.
I have a file upload system in sails.js app. I want to process the uploads before saving them in the server. My form on the client side allows multiple file uploads. Now on the server side how do I know how many files were sent?
For example I can find the total bytes to be expected from the upload using the following:
req._fileparser.form.bytesExpected
However, I couldn't find something similar that helps me find the total number of files sent to the server.
Also the above code req._fileparser.form.bytesExpected, is there a better way to get total combined file size of the files sent through the upload form by the client?
In the github repository for Skipper there is a file: index.js
Line 92 from the above file, which appears to deal with multipart file uploads, contains the following:
var hasUpstreams = req._fileparser && req._fileparser.upstreams.length;
You should check the length of upstreams in your code, and see if that contains the number of files you sent.
Another option: send a parameter in your request from the client with the number of files uploaded.
See the skipper ReadMe section about Text Parameters.
Skipper allows you to access the other non-file metadata parameters (e.g "photoCaption" or
"commentId") in the conventional way. That includes url/JSON-encoded HTTP body parameters
(req.body), querystring parameters (req.query), or "route" parameters (req.params); in other words,
all the standard stuff sent in standard AJAX uploads or HTML form submissions. And helper methods
like req.param() and req.allParams() work too.
I've just found a previous question/answer on stackoverflow.
You might try using var upload = req.file('file')._files[0].stream to access and validate, as shown in the above answer.
I am new to nodejs. I am basically using express, and I have to create a form to upload photos. So far I have created a file called upload.handlebars where I have written the following code:
<form enctype="multipart/form-data" action="uploads" method="post">
<input type="file", id = "image", name="image", accept="image/*">
<input type='submit' id='tags' value='Upload'>
I have another file called router.js where I have written the post function. One of the lines in the post function is:
fs.readFile(req.files.image.path, function (err, data) {
However, I get an error as follows:
TypeError: Cannot read property 'image' of undefined at Object.handle....
How should I specify the 'name' of the image file in my router.js?
Make sure you have multiparty middleware enabled.
https://github.com/andrewrk/connect-multiparty
Latest express doesn't come with it.
you can use express to solve this problem quickly. to know more read the folowing page express api reference
for now the following code may help you -
app.post('<your path>',express.bodyParser(),function(req,res){
console.log(req.files);//to get all the files uplaoded
});
make sure express version should 3.4
I am trying to upload multiple images at simultaneously. in server side i have to
create one unique folder for to keep that images .so how to make wait request until one request complete and send response to client. i have tried this one but when i send response i am getting this error Can't set headers after they are sent.so suggest me good solution . i am waiting for urs reply.
when i upload five images , in server side i have to check whether folder is already exist or not. if it is not exist i have to create new folder for that five images and then i have to check that folder reference is already exist or not in mongodb.if it is not exist i have to store that folder reference in mongodb.and then i have to send response to client. but here when i upload five image, five request is going to server so request is doing that terms before complete one request so same folder reference is storing and also it is creating five folder for five image.
function myMiddleware(req, res, next)
{
console.info("inside myMiddleware");
var handler = function()
{
console.info("middleware redundant. ActionDone, calling next");
next();
};
EventManager.once("finished",handler);
if (actionDone !== "working")
{
actionDone = "working";
function doneWaiting(){
// console.log("finished");
actionDone = "finished";
EventManager.emit( "finished" );
}
setTimeout(doneWaiting, 500);
}
I think that what you need here is implementing a lock on the function that checks/creates the folder and does the database check/create.
Take a look at this article to see an example