0

I'm setting up a typical profile picture upload and crop feature for a site. I'm looking at how others have set it up and I see that many are managing to have one input type="file" and it not only allows for selecting a file but also calls the PHP or JS to display the image.

I'm completely stuck on how to make it do something after the image has been chosen.

Does any one have a link or suggestion on how to perform this?

Paul
  • 298
  • 4
  • 16

2 Answers2

1

One way you could achieve this is to convert the file into a blob, then present it using an HTML5 canvas. Example: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Another option is to issue an AJAX request after the file input has been changed. Do whatever server processing you need to (crop, save, etc.) then return the AJAX call a path to the file. Then just append a new <img src='filepath.jpg' /> to the DOM.

BenR
  • 2,641
  • 1
  • 22
  • 35
  • Uploading a file directly after select is a VERY BAD idea. If the user happens to select a private image by accident, it ends up on your server. Not only could this be a huge inconvenience to the user, but if you don't cover yourself with a very good licence agreement and plenty of warnings to the user about this feature, it'll end up with a couple of lawsuits against you. – icecub Oct 02 '15 at 22:40
  • @icecub I'm not saying it's good practice, but OP asked how to do it and that's what this site is for. – BenR Oct 02 '15 at 22:42
  • No he doesn't. He's talking about a crop feature which is plain Javascript. The Javascript also displays the picture for the crop feature to work. After cropping is done, the resulting image is uploaded to the server through Ajax. As long as the user doesn't save the crop, it's never uploaded – icecub Oct 02 '15 at 22:45
  • Yes this is the case, it is loaded into a cropping tool and then uploaded from there so there is chance for the user to escape from it. I'm still not sure how to fire anything off after the file has been chosen? – Paul Oct 02 '15 at 23:23
  • Looks like this is exactly what I was looking for. The duplicate got me some new info as well just didn't find it in searches. Hard to know what to search for when your not sure of the problem. Thanks every one. – Paul Oct 03 '15 at 19:43
  • document.getElementById('files').addEventListener('change', handleFileSelect, false); That line is one big thing that I was missing. Didn't know about that event handler. It is all coming together now. – Paul Oct 03 '15 at 19:52
0

I would upload the image using AJAX, having a API receiving the image. When image has been saved the API-method returns the path of the image.

You can then display the image using the path you recieved from your API-method.