溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

node怎么使用multer進(jìn)行文件的上傳與下載

發(fā)布時(shí)間:2023-04-19 14:54:45 來(lái)源:億速云 閱讀:147 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇“node怎么使用multer進(jìn)行文件的上傳與下載”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來(lái)看看這篇“node怎么使用multer進(jìn)行文件的上傳與下載”文章吧。

首先了解下瀏覽器的自動(dòng)下載:

使用Express靜態(tài)資源中間件的默認(rèn)行為是在瀏覽器中展示靜態(tài)文件,而不是自動(dòng)下載。

如果需要訪(fǎng)問(wèn)靜態(tài)資源時(shí)自動(dòng)下載,可以在HTTP響應(yīng)中設(shè)置Content-Disposition頭。Content-Disposition頭指示瀏覽器以何種方式處理要下載的文件。

常見(jiàn)的Content-Disposition值有"inline"和"attachment"。當(dāng)Content-Disposition的值為"attachment"時(shí),瀏覽器會(huì)自動(dòng)下載文件,示例代碼如下:

app.use('/uploads', express.static(__dirname + '/uploads', {
  setHeaders: (res, path) => {
    res.setHeader('Content-Disposition', 'attachment');
  }
}));

再來(lái)了解下multer:

Multer是一個(gè)Node.js中間件,用于處理表單數(shù)據(jù)中的multipart/form-data類(lèi)型。主要用于上傳文件,將上傳的文件保存到指定的目錄中。

Multer還提供了多個(gè)方法,這些方法可以根據(jù)不同的需求設(shè)置文件上傳的行為。比如:single()方法用于上傳單個(gè)文件,none()方法表示不接受任何文件,fields()方法用于上傳多個(gè)字段的文件,limits屬性用于限制上傳文件的大小等

接下來(lái)開(kāi)始準(zhǔn)備:

//html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>圖片上傳</title>
</head>
<body>
  <input type="file" id="fileInput">
  <br><br>
  <button onclick="upload()">上傳</button>
  
  <script>
    function upload() {
      const formData = new FormData()
      formData.append('image', document.getElementById('fileInput').files[0])
      
      fetch('http://127.0.0.1:3000/upload', {
        method: 'POST',
        body: formData
      })
      .then(response => response.text())
      .then(result => {
        console.log(result)
      })
    }
  </script>
</body>
</html>
//app.js
const express = require('express')
const app = express()
 
// 創(chuàng)建上傳路由
app.post('/upload', (req, res) => {
  res.send('hello world')
})
 
// 啟動(dòng)服務(wù)器
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000')
})

 安裝Multer,npm i Multer,根目錄新建一個(gè)uploads文件夾 然后對(duì)app.js進(jìn)行配置:就實(shí)現(xiàn)了文件上傳

const express = require('express')
const multer = require('multer')
const path = require('path')
 
const app = express()
 
// diskStorage創(chuàng)建上傳存儲(chǔ)器 
const storage = multer.diskStorage({
  // 設(shè)置上傳文件存儲(chǔ)目錄
  destination: function (req, file, cb) {
    cb(null, './uploads/') 
  },
  //保存在 uploads 中的文件名
  filename: function (req, file, cb) {
    const extname = path.extname(file.originalname) // 獲取文件后綴名
    const filename = Date.now() + '-' + extname     // 時(shí)間戳+后綴名 生成唯一文件名
    cb(null, filename)
  }
})
 
//創(chuàng)建一個(gè)名為upload的文件上傳示例
const upload = multer({ storage: storage })
 
// 創(chuàng)建上傳路由
// upload.single('image') 處理單個(gè)文件上傳
app.post('/upload', upload.single('image'), (req, res) => {
  const file = req.file
  if (!file) {
    return res.status(400).send('請(qǐng)選擇要上傳的圖片')
  }
  res.send('上傳成功')
})
 
// 啟動(dòng)服務(wù)器
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000')
})

然后實(shí)現(xiàn)文件下載,也是對(duì)app.js進(jìn)行配置:url+uploads+上傳的文件就可以實(shí)現(xiàn)下載

const express = require('express')
const multer = require('multer')
const path = require('path')
 
const app = express()
 
XXXXXXXXXXXXXXX 跟上面一樣的
 
app.use('/uploads', express.static(__dirname + '/uploads', {
  setHeaders: (res, path) => {
    // 當(dāng)Content-Disposition的值為"attachment"時(shí),瀏覽器會(huì)自動(dòng)下載文件
    res.setHeader('Content-Disposition', 'attachment');
  }
}));
 
// 啟動(dòng)服務(wù)器
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000')
})

以上就是關(guān)于“node怎么使用multer進(jìn)行文件的上傳與下載”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI