File upload normally uses input type= “file” but this default is too ugly so we can call click
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta http-equiv=" x-UA-compatible "content="ie=edge"> <title>Document</title> <style> span{display: inline-block; width: 100px; height: 30px; line-height: 30px; border-radius: 8px; overflow: hidden; text-align: center; color: white; background: red; margin: </style> </head> <body> <input type="file"> <span> Upload </span> </body> <script SRC = "https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js" > < / script > < script > < / script > < / HTML >Copy the code
It’s nice to write simple events in JQ with a simple configuration structure
Bind events in JS
$('span').click(function(){$('input').click() => spanCopy the code
Create a new IMG tag
<input type="file"> <span> upload </span> <img SRC ="" Alt =""> unmarked SRCCopy the code
Window.url
URL object is hard disk (SD card, etc.) to file a path, file upload, if we do not want to upload server side cases, upload pictures when rendering window. But in order to pass the var URL = URL. CreateObjectURL (obj) files [0]). Get an HTTP url path, which can be set toIs shown in.
$('src').attr({'src':window.URL.createObjectURL(obj.files[0])})
Copy the code
So the image will show up? The answer is no
The URL state under window has been judged when the web page is loaded, so we need to judge again when we upload, through the change method of input
$('input').change(function(ev){var files = ev.target.files; var url=window.URL.createObjectURL(files[0]) $('img').attr({'src':url}) })Copy the code
Now let’s look at a simple direct call
<span> upload </span> <img SRC ="" Alt ="">Copy the code
Define methods in JS
function change(e){
}
Copy the code
And start editing
Function change (e) {var files = e.f iles $(" img "). Attr ({' SRC ': window. URL. CreateObjectURL (files [0])}) = > so we can get to the path}Copy the code
Both methods can refer directly to the method to get the data without adding target and then call the change method to add target
Once you get the data you can get more data like the file size
function change(e){
var files=e.files
console.log(e.files[0].size)
$('img').attr({'src':window.URL.createObjectURL(files[0])})
}
Copy the code
Get more data from the file and print it slowly!!