上传图片并回显

功能:上传图片后,由服务器返回显示图片

1
2
3
4
5
6
<form>
<input type="file" name="image" id="image">
<input type="button" name="submit" id="submit" value="submit">
</form>
<div class="display" id="display"></div>
<script src="./index.js"></script>
1
2
3
4
5
6
7
8
9
10
.display {
width: 300px;
height: 300px;
border: 1px solid #ccc;
box-shadow: 0 0 2px #ddd;
}
.display img {
width: 100%;
height: 100%;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var postURL = "http://10.103.241.137:8888/upload";
document.getElementById("submit").onclick = function(){
var data = new FormData()
var file = document.getElementById("image").files[0]
data.append("image", file)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
var img = null;
if (document.getElementsByTagName("img")[0]) {
img = document.getElementsByTagName("img")[0]
} else {
img = document.createElement("img")
document.getElementById("display").appendChild(img)
}
img.src = JSON.parse(xhr.responseText).url
}
}
}
xhr.open("Post", postURL, true)
xhr.send(data)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// nodejs
var http = require("http"),
url = require("url"),
formidable = require("formidable"),
fs = require("fs");
http.createServer(function(req, res){
console.log("request for url: "+ req.url)
res.setHeader('Access-Control-Allow-Origin', '*');
if (url.parse(req.url).pathname == "/upload") {
var form = formidable.IncomingForm();
form.uploadDir = "../tmp"
form.keepExtensions = true
form.parse(req,function(err, fields, files) {
if (err) {
console.log(err)
} else {
console.log(files)
fs.renameSync(files.image.path, '../tmp/'+files.image.name)
res.writeHead(200, {"content-type": "application/json"})
var body = JSON.stringify({
url: "http://10.103.241.137:8888/image/"+files.image.name
})
res.write(body)
res.end()
}
})
}
if (/^\/image\/.*/.test(url.parse(req.url).pathname)) {
var imgPath = "../tmp/" + url.parse(req.url).pathname.replace("/image/","")
fs.readFile(imgPath, function(err, file) {
if (err) {
res.writeHead(500, {"content-type": "text/plain"})
res.write(err + "\n")
res.end()
} else {
res.writeHead(200, {"content-type": "image/jpeg"})
res.write(file, "binary")
res.end()
}
})
}
}).listen(8888)