NodeJS文件上傳

使用multer上傳文件,默認(rèn)不會(huì)給文件添加擴(kuò)展名

一、package.json

{
  "name": "file_upload",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "axios": "^0.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "multer": "^1.4.2",
    "randomstring": "^1.1.5",
    "vue": "^2.6.10"
  }
}

二、app.js

var express = require('express')
var multer = require('multer')
var randomstring = require('randomstring')
var path = require('path')
var app = express()

app.use(require('cors')())
app.use(express.json())

// 指定上傳文件的存儲(chǔ)目錄及文件名
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads')
  },
  filename: function (req, file, cb) {
    var ext = path.extname(file.originalname)
    cb(null, randomstring.generate(44) + ext)
  }
})

var upload = multer({storage: storage})

app.post('/upload', upload.single('file'), (req, res) => {
  var file = req.file
  console.log(file)
  if (file) {
    file.url = `http://localhost:3000/${file.filename}`
    res.send(file)
  } else {
    res.send({
      msg: '老鐵,別皮了,請(qǐng)上傳文件吧'
    })
  }
})

// 靜態(tài)資源訪問(wèn)
app.use(express.static('uploads'))
app.use(express.static('public'))

app.listen(3000, () => {
  console.log('http://localhost:3000')
})

三、upload_test.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="node_modules/axios/dist/axios.min.js"></script>
  <script src="node_modules/vue/dist/vue.min.js"></script>
</head>
<body>
<div id="app">
  <form @submit.prevent="upload" action="">
    <p>
      <input @change="fn" ref="file" type="file">
    </p>
    <p>
      <input type="submit">
    </p>
  </form>
</div>
<script>
  var http = axios.create({
    baseURL: 'http://localhost:3000'
  })

  Vue.config.productionTip = false
  Vue.prototype.$http = http


  new Vue({
    el: '#app',
    methods: {
      fn(){
        console.log(this.$refs.file.files)
      },
      upload() {
        var formData = new FormData()
        formData.append('file', this.$refs.file.files[0])
        this.$http.post('/upload', formData, {
          headers: {
            'content-type': 'multipart/form-data'
          }
        }).then((res) => {
          console.log(res.data)
        }).catch((err) => {
          console.log(err)
        })
      }
    }
  })
</script>
</body>
</html>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容