html部分
html
<h1>文件上傳</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="pic" multiple ref="pic">
<input type="button" @click="uploadFile" value="上傳">
</form>複製代碼
uploadFile() {
//拿到上傳的圖片
var imgs = this.$refs.pic.files;
for (let i = 0; i < imgs.length; i++) {
//逐個獲取圖片
let file = imgs[i];
//使用createObjectURL方法生成圖片縮略圖預覽
let src = window.URL.createObjectURL(file);
//上傳該圖片到服務器端並拿到返回的服務器端圖片地址
let url = await uploadImg(file, this.$data.urlList);
//構造數組
this.$data.urlList.push({
src: src,
name: file.name,
url: "localhost/" + url
});
}}複製代碼
//上傳一個圖片文件async function uploadImg(file, urlList) {
var formData = new FormData();
formData.append("pic", file);
let url = await new Promise((resolve, reject) => {
axios.post('/upload', formData, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then((res) => {
resolve(res.data);
})
.catch((err) => {
console.log(err);
});
})
//返回服務器上對應地址
return url;
}複製代碼
let url = await uploadImg(file, this.$data.urlList);複製代碼
app.post("/upload", function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
let imgPath = files.pic.path
let imgName = files.pic.name
// 同步讀取文件
let data = fs.readFileSync(imgPath)
// 存儲上傳的圖片,同時獲取靜態圖片地址並返回客戶端
fs.writeFile("static/" + imgName, data, function(err) {
if (err) {
console.log(err)
return;
}
let itemUrl = {
"path": "static/" + imgName
};
let url = "static/" + imgName;
res.send(url);
})
})
});複製代碼
<h1>圖片列表</h1><div class="img-wrapper">
<div class="uploading" v-for="(item, index) in urlList" :key="index">
<div>
<img class="uploading-image" :src="item.src" alt="">
</div>
<div class="uploading-info">
<span class="uploading-name">
<a target="_blank" :href="item.src">{{ item.name }}</a>
</span>
<span class="copy" :data-clipboard-text="item.url">複製</span>
</div>
</div>
</div>複製代碼
downloadURL() {
var imgURLS = [];
//設置excel標題
imgURLS.push(["序號", "圖片名稱", "URL連接"]);
//獲取全部圖片url連接信息
this.$data.urlList.forEach((item, index) => {
//構建一個數組
var itemArray = [index + 1].concat(item.name, item.url);
//構建二維數組
imgURLS.push(itemArray);
});
//生成工做表結構
const ws = XLSX.utils.aoa_to_sheet(imgURLS);
//設置三列單元格寬度
var wscols = [{
wch: 6
}, {
wch: 50
}, {
wch: 50
}];
ws['!cols'] = wscols;
//生成excel基本數據結構
const wb = XLSX.utils.book_new();
//生成表名字爲SheetJS的excel工做區
XLSX.utils.book_append_sheet(wb, ws, "SheetJS");
//導出excel
XLSX.writeFile(wb, "export.xlsx");}複製代碼
npm install
node app
瀏覽器輸入: localhost複製代碼