0

Okay, so I have been having trouble with creating an HTML site with a user-changeable profile picture. For example, being able to upload and change your profile picture on social media. I'm rather new, but not a complete noob. So, please keep terms plain-ish. I've tried many methods, so I really can't put any code down for revision, but here's what I thought should work:

<p><img src="my_file" alt="my_file" style="float:left;width:100px;height:100px;">Your Profile Picture</p>
<input type="file" name="my_file" id="my-file">

<div id="update"> - Save your Picture</div>
<center>
    <div id="edit" contenteditable="true" style="text-size:150%">
</center>
<input type="button" value="Save changes" onclick="saveEdits()"/>
DimaSan
  • 10,315
  • 10
  • 56
  • 68
Will H.
  • 1
  • 1

1 Answers1

2

Previewing the image

HTML:

<img id="profile-pic" alt="Profile picture" />
<h2>
  Your profile picture
</h2>

<input type="file" id="my-file" />
<br>
<input type="button" value="Save changes" id="save" />

JavaScript:

document.getElementById("my-file").onchange = function() {
  if (this.files && this.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      // e.target.result is a base64-encoded url that contains the image data
      document.getElementById('profile-pic').setAttribute('src', e.target.result);
    };
    reader.readAsDataURL(this.files[0]);
  }
}

Code adapted from this answer by Ivan Baev.

CSS:

#profile-pic {
  float: left;
  margin-right: 20px;
  /* If you want to crop the image to a certain size, use something like this */
  object-fit: cover;
  width: 100px;
  height: 100px;
}

Cropping code adapted from this answer by Vision Hive.

(JSFiddle)

Saving it

If you're trying to save the image so other users will see it, things get complicated. Especially with different pictures for different users, you'd want some sort of database to keep track of profiles and a server-side program to display the right one at the right time. If you're new to server programming, you can find tutorials for a language of your choice (or if you want to stick to JavaScript, see Node.js). There's a good chance StackOverflow has an answer for how to accept image uploads in your language. Once your server is ready to accept an image, take a look at this answer by Rudie for how to upload it from the browser.

Community
  • 1
  • 1
user6939352
  • 399
  • 4
  • 7