Trigger file upload via Javascript only

2019-09-17 06:19发布

I want to write a browser add-on that automatically upload file on the page. So this will be done in pure Javascript.

This is what I have / know:

  1. input#someId of the file upload input

  2. File name and location in the computer

I am trying to "hardcode" in the console for now as a "Proof of Concept" but I cannot get it to work.

I have tried these two methods:

  1. inputElement.click() as inputElement is the querySelector of that input.

  2. Use initMouseEvent from what's the equivalent of jquery's 'trigger' method without jquery? but gave me error Uncaught TypeError: Cannot read property 'dispatchEvent' of null

So my questions are:

  1. How to trigger click input of file upload element?

  2. Better: how to process the upload completely? Basically pass the filename+location for upload to start (like when user clicks OK to open the file from the dialog)

UPDATE 1:

I was reading this http://www.thecssninja.com/javascript/fileapi Maybe uploading file from File System is not possible. How about these alternatives:

  1. We can grab a file from url (http)

  2. The file is just image and in Javascript memory (base64)

Anyone of the above should be OK if they can be automatically upload and bypass the dialog box and search the file via local File System. I am thinking what if the image DOM or even canvas can be just dragged?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-09-17 07:21

As people commented, you cannot do that. For security reasons, you have absolutely no access to programmatic fill an file input. Think about it, some dude could add a simple script to steal files from your computer and you wouldn't even know!

As far as I know, can't be done.

查看更多
登录 后发表回答