前端代碼 文件名:register.html NodeJS代碼 下載所需要的模塊 ...
前端代碼
文件名:register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="file" id="upfile">
<button onclick="submit()">提交</button>
<img src="#" alt="" id="img">
<a href="" id="download" download="a.jpg">點我下載</a>
<script>
function submit () {
var img = document.getElementById('img');
var download = document.getElementById('download');
var file = document.getElementById('upfile');
//利用htmlAPI FormData
var formData = new FormData();
formData.append('img',file.files[0]);
//發送請求
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = ActiveXObject();
}
xhr.open('post','/imgData',true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var res = JSON.parse(xhr.responseText);
// 這一步,將上傳成功之後,後端傳回來一個地址,繼續發送請求數據,後端只管讀取數據返回就行,瀏覽器會自動識別
img.src = '/getImgData?path=' + res.path;
//下載,給a標簽加上一個download屬性就行,後端只管讀取數據返回
download.href = '/getImgData?path=' + res.path;
}
}
xhr.send(formData);
}
</script>
</body>
</html>
NodeJS代碼
下載所需要的模塊
npm install express
npm install multer
var express = require('express');
var url = require('url');
var fs = require('fs');
var multer = require('multer'); //處理上傳的文件模塊
var app = new express();
var uploadSingle = multer({dest: './uploadFile/'}); //dest: 配置預設上傳之後存儲的文件夾
//這個返回的前端代碼頁面
app.get('/login',function (req,resp) {
var loginhtml = fs.readFileSync('./register.html');
resp.end(loginhtml);
})
//處理多張圖片上傳的時候,用uploadSingle.array('img),則request.file得到的是一個數組
//single裡面的'img'要與前端上傳時的name屬性的值一致
app.post('/imgData',uploadSingle.single('img'),function (request,response) {
// 上傳之後會自動保存到定義的文件夾下,一些相關信息在request.file當中
var path = request.file.path;
// ...存儲到資料庫等操作,把得到的存儲地址返回給前端,用於後面前端好發送請求讀取數據
})
app.get('/getImgData',function (request,response) {
//得到前端傳遞過來的要讀取的文件的路徑
var path = url.parse(request.url,true).query;
try {
var data = fs.readFileSync(path);
//返回讀取到的數據
}catch(e) {
//讀取發生錯誤。。
}
})
app.listen(8081,function () {
console.log('服務已啟動');
})