2

I have some client-side JavaScript which will output a jpeg file based on HTML5 canvas manipulation, if the user performs an action such as clicking the "OK" button.

I would like the jpeg output to be automatically loaded into the "Upload Front Side" field in a form, as if the user uploaded the file from his or her own hard drive.

However, I can't seem to get it to work.

Here is the form:

<div class="property-wrapper">
    <label for="upload-front">Upload Front Side</label>
    <input id="upload" class="file" type="file" enctype="multipart/form-data" id="Front-Side" name="properties[Front Side]" onchange="readURL(this);" accept="image/*" /> 
</div>
<script>
    document.getElementById('upload').value="http://upload.wikimedia.org/wikipedia/commons/thumb/2/22/Turkish_Van_Cat.jpg/353px-Turkish_Van_Cat.jpg"
</script>
Mike-O
  • 844
  • 1
  • 11
  • 16

3 Answers3

5

The problem is browsers have several restrictions on what can be done programatically with file upload due to security reasons, have a look at this answer.

The file upload functionality is potentially exploitable, and some browsers will for example not open the explorer box if for example the file upload input field is hidden with display:none.

Most browsers will not allow programatic clicks to a file upload element and require the user to click them instead, to prevent attacks where someone sends a link to a page that immediately steals content from the user's hard drive.

So the functionality you mention does not seem to be feasible due to common browser security restrictions. There are usually no error messages or warnings, it just doesn't work.

An alternative to using the file upload browser input component could be to encode the contents of the file in Base64 and send in the body of an ajax POST for example.

Community
  • 1
  • 1
Angular University
  • 42,341
  • 15
  • 74
  • 81
0

Are you asking how to upload to a server, via a form, the graphic image you extracted from the canvas of your page? This would be useful, I hope to see this answered.

I would start by enabling the user to download/export the image. This might be done with a blob. Ive done this for text data exports, works nicely.

Maybe there is a way to apply the same tricks, just feed the blob/buffer to the server.

Another path might be to "PUT" the file at the server.

Hope this helps.

dfowler7437
  • 461
  • 2
  • 9
0

I would ajax POST a base64 encoded string of the image and forget the whole file upload thingy. You can upload the canvas code directly and reconvert it server side if you need a preview or something or see what other outputs are available from your canvas/image converter code.

I am assuming you are uploading to same server so you would not have cross domain issue but otherwise you can setup your server to accept cross domain ajax request very easily.

cyberwombat
  • 38,105
  • 35
  • 175
  • 251