前端vue+express實現(xiàn)文件的上傳下載示例
新建server.js
yarn init -y
yarn add express nodemon -D
var express = require("express");
const fs = require("fs");
var path = require("path");
const multer = require("multer"); //指定路徑的
var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 前端解決跨域問題
app.all("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
// 訪問靜態(tài)資源
app.use(express.static(path.join(__dirname)));
// 文件上傳
app.post("/upload", multer({ dest: "./public" }).any(), (req, res) => {
const { fieldname, originalname } = req.files[0];
// 創(chuàng)建一個新路徑
const name = fieldname.slice(0, fieldname.indexOf("."));
const newName = "public/" + name + path.parse(originalname).ext;
fs.rename(req.files[0].path, newName, function (err) {
if (err) {
res.send({ code: 0, msg: "上傳失敗", data: [] });
} else {
res.send({ code: 1, msg: "上傳成功", data: newName });
}
});
});
// 文件下載
app.get('/download', function(req, res) {
res.download('./public/test.xls');
});
// 圖片下載
app.get('/download/img', function(req, res) {
res.download('./public/2.jpg');
});
let port = 9527;
app.listen(port, () => console.log(`端口啟動: http://localhost:${port}`));
(1):前端文件上傳請求
第一種: form表單
<form action="http://localhost:9527/upload" method="POST" encType="multipart/form-data">
<input type="file" name="user"/>
<input type="submit" />
</form>

第一種: input輸入框
<input type="file" @change="changeHandler($event)"/>
changeHandler(event) {
let files = event.target.files[0];
console.log("files",files)
let data = new FormData();
data.append(files.name,files);
console.log("data",data)
axios.post("http://localhost:9527/upload",data,{
headers:{
"Content-Type":"multipart/form-data"
}
}).then(res =>{
console.log("res",res)
})
},
(2):前端文件下載
第一種: 后端返回一個下載的鏈接地址,前端直接使用 即可
第二種: 使用二進制流文件下載
<input type="button" value="點擊下載" @click="handleDownload">
handleDownload() {
axios({
method: 'get',
url: "http://localhost:9527/download",
data: {
test: "test data"
},
responseType: "arraybuffer" // arraybuffer是js中提供處理二進制的接口
}).then(response => {
// 用返回二進制數(shù)據(jù)創(chuàng)建一個Blob實例
if(!response) return;
let blob = new Blob([response.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}) // for .xlsx files
// 通過URL.createObjectURL生成文件路徑
let url = window.URL.createObjectURL(blob)
console.log("url==========",url)
// 創(chuàng)建a標簽
let ele = document.createElement("a")
ele.style.display = 'none'
// 設(shè)置href屬性為文件路徑,download屬性可以設(shè)置文件名稱
ele.href = url
ele.download = this.name
// 將a標簽添加到頁面并模擬點擊
document.querySelectorAll("body")[0].appendChild(ele)
ele.click()
// 移除a標簽
ele.remove()
});
},
(3) 附加:二進制流圖片的下載
// 二進制流圖片文件的下載
downLoadImg() {
axios({
method: 'get',
url: `http://localhost:9527/download/img`,
responseType: 'arraybuffer',
params: {
id: 12
}
}).then(res => {
var src = 'data:image/jpg;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
// this.srcImg = src // 圖片回顯
var a = document.createElement('a')
a.href = src
a.download = '2.jpg'
a.click()
a.remove()
})
}
到此這篇關(guān)于前端vue+express實現(xiàn)文件的上傳下載示例的文章就介紹到這了,更多相關(guān)vue express文件上傳下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3實現(xiàn)轉(zhuǎn)盤抽獎效果的示例詳解
這篇文章主要為大家詳細介紹了如何通過Vue3實現(xiàn)簡單的轉(zhuǎn)盤抽獎效果,文中的示例代碼講解詳細,具有一定的借鑒價值,感興趣的可以了解一下2023-10-10
Vue移動端下拉加載更多數(shù)據(jù)onload實現(xiàn)方法淺析
這篇文章主要介紹了Vue移動端下拉加載更多數(shù)據(jù)onload實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
詳解如何在Vue3+TS的項目中使用NProgress進度條
本文主要介紹了詳解如何在Vue3+TS的項目中使用NProgress進度條,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06
vue實現(xiàn)ajax滾動下拉加載,同時具有l(wèi)oading效果(推薦)
這篇文章主要介紹了vue實現(xiàn)ajax滾動下拉加載,同時具有l(wèi)oading效果的實現(xiàn)代碼,文章包括難點說明,介紹的非常詳細,感興趣的朋友參考下2017-01-01
vue3.x使用swiperUI動態(tài)加載圖片失敗的解決方法
這篇文章主要為大家詳細介紹了vue3.x使用swiperUI動態(tài)加載圖片失敗的解決方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07
vue3+ts項目中.env配置環(huán)境變量與情景配置方式
本文介紹了如何在Vite中配置環(huán)境變量和不同的運行模式,環(huán)境變量文件以.env開頭,僅VITE_前綴的變量會被暴露,開發(fā)模式加載.env.development,生產(chǎn)模式加載.env.production,NODE_ENV用于區(qū)分開發(fā)和生產(chǎn)環(huán)境2024-10-10

