上传
1 2 3 4
| <div class="upload"> <input type="file" name="file" @change="change" /> <button @click="upload">上传</button> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| upload() { let formData = new FormData(); formData.append("file", this.file); axios .post("http://localhost:3000/request/profile", formData) .then((res) => { console.log(res.data); }); }, change(e) { let file = e.target.files[0]; console.log(file); this.file = file; }
|
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
| const express = require('express') const router = express.Router() const multer = require('multer')
const uploadFolder = './upload/' const fs = require('fs') function createUploadFolder(folder) { try { fs.accessSync(folder) } catch (e) { fs.mkdirSync(folder) } } createUploadFolder(uploadFolder)
let storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, uploadFolder) }, filename: function (req, file, cb) { cb(null, file.originalname) } }) let upload = multer({storage}) router.post('/profile',upload.single('file'),(req, res) => { res.send({msg: 'upload success'}) })
module.exports = router
|
结果就可以看到服务器上upload文件夹下生成上传的文件
下载
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
| download() { axios .post( "http://localhost:3000/request/download", { name: this.name, }, { responseType: "blob", } ) .then((res) => { debugger; const content = res.data; const blob = new Blob([content]); const fileName = "12.txt"; if ("download" in document.createElement("a")) { const link = document.createElement("a"); const href = window.URL.createObjectURL(blob); link.href = href; link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(href); } else { navigator.msSaveBlob(blob, fileName); } }); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| const express = require('express') const router = express.Router() const fs = require('fs')
router.post('/download', (req, res) => { let name = req.body.name let path = './upload/' + name res.set({ 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=' + name }) fs.createReadStream(path).pipe(res) })
|
结果点击下载弹出保存位置,然后可以进行保存。
参考: