When users register their accounts or modify their profiles, they will need to select a picture locally as their profile picture and preview it at the same time.

There are two common ideas: one is to upload the image to a temporary folder on the server, and return the URL of the image, and then render in HTML page; Another idea is to preview the image directly in local memory, and then upload it to the server for saving after the user confirms the submission.

Both methods have advantages and disadvantages. Method one obviously wastes traffic and server resources. The second method increases the burden of the browser and requires higher compatibility of the browser.

Here is a preview of the image directly in the local memory, the user confirmed the submission and then uploaded to the server to save this method

html
<div class="reHead"> <P class="content-format"> </P> <div class="content"> <form method="post" encType ="multipart/form-data" id="file_upload" class="headForm"> <div id="test-image-preview" class="iconfont icon-bianjitouxiang"> <input type="file" name="test" id="test-image-file" class="fileHead" accept="image/gif, image/jpeg, image/png, Image/JPG "multiple ="multiple"> </div> <div class="headMain"> <span class="file"> </span> <p id="test-file-info" class="fileName"></p> </div> </form> </div> <div class="but"> <button class=" orangeHead" id="upImgSub"><a href="" Title = "edit information" target = "_blank" > save < / a > < / button > < / div > < / div >Copy the code
Js upload profile picture
<script type="text/javascript" src="./jquery.min.js"></script> <script> var fileInput = document.getElementById('test-image-file'), info = document.getElementById('test-file-info'), preview = document.getElementById('test-image-preview'); dataBase64 = '', // preview.style.backgroundImage = 'url(.. /.. /img/portrait.png)'; / / the default display picture / / to monitor change event: the fileInput. AddEventListener (' change 'upImg); / / image upload function logic function upImg () {preview. Style. The backgroundImage = ' '; // Clear the background image if (! Fileinput.value) {// Check whether the file is selected: $('#test-image-preview').addclass ('icon-bianjitouxiang'); Info.innerhtml = 'No file selected '; }else{ $('#test-image-preview').removeClass('icon-bianjitouxiang'); info.innerHTML = ''; } var file = fileInput.files[0]; Var size = file.size; If (size >= 1 * 1024 * 1024) {// Determine the size of the file info.innerhtml = 'The file is larger than 1 MB! '; preview.style.backgroundImage = ''; $('#test-image-preview').addClass('icon-bianjitouxiang'); return false; } if (file.type ! == 'image/jpeg' && file.type ! == 'image/png' && file.type ! == 'image/ GIF ') {// Get File info: info.innerhtml = 'Not a valid image File! '; preview.style.backgroundImage = ''; $('#test-image-preview').addClass('icon-bianjitouxiang'); return; } var reader = new FileReader(); reader.onload = function (e) { dataBase64 = e.target.result; // 'data:image/jpeg; base64,/9j/4AAQSk... (base64 encoding)... }' preview.style.backgroundImage = 'url(' + dataBase64 + ') '; preview.style.backgroundRepeat = 'no-repeat'; preview.style.backgroundSize = ' 100% 100%'; }; // Read the file as a DataURL: read.readasdataurl (file); // console.log(file); }Copy the code
Js submits the avatar to the server
$("#upImgSub").click(function () { $.ajax({ type:'post', data:{'newHead':dataBase64}, async:false, // Async is synchronous when the async property value is false. Ajax requests lock the entire browser and only execute Ajax alert statements after Ajax requests return results. // Async is asynchronous when the value of the async property is true, meaning that the ajax request does not wait for the result to be returned, and the ajax alert statement is executed directly. DataType :'json', URL :'/index/img', If (res.code === 200){alert(MSG)}else{alert(MSG) // alert(MSG)}}, Error :function () {alert(" interface error "); // Return failure}})});Copy the code

Async is synchronous when the async property value is false. Ajax requests lock the entire browser and only execute Ajax alert statements after Ajax requests return results. (Possible, but not recommended) Async is asynchronous when the value of the async property is true, meaning that the ajax request does not wait for the result to be returned and the ajax alert statement is executed directly. (Later on asynchronous request resolution back to Hell)

css
body{
    font-size: 12px;
}
.reHead{
    margin: 15px 4%; 
}
.headForm{
    text-align: center;
    padding: 40px 0 70px 0;
}
#test-image-preview {
    position: relative;
    display: inline-block;
    width: 100px;
    height: 100px;
    border-radius: 50px;
    background: #F5F5F5;
    color: #fff;
    font-size: 60px;
    text-align: center;
    line-height: 100px;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center center;
    margin-bottom: 26px;
}
.fileHead{
    position: absolute;
    width: 100px;
    height: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.content-format {
    font-size: 12px;
    font-weight: 400;
    color: rgba(153, 153, 153, 1);
}
.headMain{
    height: 40px;
}
.file {
    position: relative;
    background: #fff;
    color: #F39800;
    font-weight:800;
}
.file input {
    position: absolute;
    font-size: 12px;
    right: 0;
    top: 0;
    opacity: 0;
}
.fileName {
    line-height: 28px;
    font-size: 12px;
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
}
.but{
    text-align: center;
}
.orangeHead{
    width: 40%;
    height: 40px;
    background: #f60;
    border: none;
}
.orangeHead a{
    color: #fff;
}
Copy the code

This completes the function of uploading and submitting the profile picture, and the display effect is as follows:

Code word is not easy, for attention like, more technology welcome to [an umbrella bone] home page 1. Using the session in vue Storage and store user login state vuex 2. Vue | use elementUi on-demand introduction of component method and the question 3. Vue | mobile terminal or PC render different page 4. Vue | The router routing dynamically linked and carry id into details page three models of 5. Vue | routing to jump back to the top