上传图片并回显 发表于 2017-12-19 | 分类于 前端 功能:上传图片后,由服务器返回显示图片 123456<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> 12345678910.display { width: 300px; height: 300px; border: 1px solid #ccc; box-shadow: 0 0 2px #ddd;}.display img { width: 100%; height: 100%;} 1234567891011121314151617181920212223242526var 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)} 12345678910111213141516171819202122232425262728293031323334353637383940414243// nodejsvar 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)