Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prepare jsHandle.uploadFile for CDP Page.handleFileChooser removal #5196

Merged
merged 2 commits into from Dec 3, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 19 additions & 4 deletions lib/JSHandle.js
Expand Up @@ -14,9 +14,12 @@
* limitations under the License.
*/

const {helper, assert, debugError} = require('./helper');
const fs = require('fs');
const path = require('path');

const {helper, assert, debugError} = require('./helper');
const readFileAsync = helper.promisify(fs.readFile);

function createJSHandle(context, remoteObject) {
const frame = context.frame();
if (remoteObject.subtype === 'node' && frame) {
Expand Down Expand Up @@ -312,9 +315,21 @@ class ElementHandle extends JSHandle {
* @param {!Array<string>} filePaths
*/
async uploadFile(...filePaths) {
const files = filePaths.map(filePath => path.resolve(filePath));
const objectId = this._remoteObject.objectId;
await this._client.send('DOM.setFileInputFiles', { objectId, files });
const promises = filePaths.map(filePath => readFileAsync(filePath, 'utf8'));
const buffers = await Promise.all(promises);
const fileContents = buffers.map(buffer => buffer.toString());
mathiasbynens marked this conversation as resolved.
Show resolved Hide resolved
filePaths = filePaths.map(filePath => path.basename(filePath));
await this.evaluateHandle((element, filePaths, fileContents) => {
const dt = new DataTransfer();
for (let i = 0; i < filePaths.length; i++) {
const name = filePaths[i];
const content = fileContents[i];
const file = new File([content], name);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const result = await fetch(`data:${files[i].mimeType};base64,${files[i].content}`);
const file = new File([await result.blob()], files[i].name);

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where are you getting mimeType from? Are you suggesting we introduce a dependency on mime-types, or am I missing some trick?

dt.items.add(file);
}
element.files = dt.files;
element.dispatchEvent(new Event('input', { 'bubbles': true }));
}, filePaths, fileContents);
}

async tap() {
Expand Down