国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

node之本地服務器圖片上傳的方法示例

2024-05-06 15:41:21
字體:
來源:轉載
供稿:網友

在自己做一個簡單的后臺管理系統時,用的是node作本地數據庫,然后用了Element-ui的upload組件來實現圖片的上傳,中間有遇到那么點小坑,這里記錄下,比較坑的一點就是,不知道文件的命名不能帶空格,然后改了好久

1.index.vue文件

這里的話,就是簡單點的使用圖形界面框架Element-ui的上傳組件,然后,action就是服務器端的地址,我這里使用了代理,將localhost:8080代理到你使用node作為服務器的地址就可以了

<template>  <div class="avatar">   <img    :src="avatar?avatar:defaultImg"   />  </div>  <el-upload   class="upload-demo"   drag   action="http://localhost:8080/api/upload"   :show-file-list="false"   :on-success="uploadImgSuccess"  >   <i class="el-icon-upload"></i>   <div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em></div>  </el-upload></template><script>import defaultImg from '@/assets/img/avatar.png'export default{  data() {    return {      avatar: ''    }  },  methods: {    uploadImgSuccess(res) {      this.avatar = res.result.url;    }  }}</script>

2.代理文件

我這里使用的是vue-cli3腳手架來搭建的項目,所以,自己在項目的根目錄下創建一個vue.config.js來做一些配置

module.exports = { devServer: {  port: 8080,  headers: {  },  inline: true,  overlay: true,  stats: 'errors-only',  proxy: {   '/api': {    target: 'http://127.0.0.1:3000',    changeOrigin: true // 是否跨域   }  } },};

3.node服務器端文件

這里很重要的一點就是設置靜態資源目錄

app.use('/serverImage', express.static(path.join(__dirname, 'serverImage')));

對圖片上傳進行了方法的封裝

const fs = require('fs');const path = require('path');/* formidable用于解析表單數據,特別是文件上傳 */const formidable = require('formidable');/* 用于時間格式化 */const formatTime = require('silly-datetime');/* 圖片上傳 */module.exports = (req, res) => { /* 創建上傳表單 */ let form = new formidable.IncomingForm(); /* 設置編碼格式 */ form.encoding = 'utf-8'; /* 設置上傳目錄(這個目錄必須先創建好) */ form.uploadDir = path.join(__dirname, '../serverImage'); /* 保留文件后綴名 */ form.keepExtensions = true; /* 設置文件大小 */ form.maxFieldsSize = 2 * 1024 *1024; /* 格式化form數據 */ form.parse(req, (err, fields, files) => {  let file = files.file;  /* 如果出錯,則攔截 */  if(err) {   return res.send({'status': 500, msg: '服務器內部錯誤', result: ''});  }  if(file.size > form.maxFieldsSize) {   fs.unlink(file.path);   return res.send({'status': -1, 'msg': '圖片不能超過2M', result: ''});  }  /* 存儲后綴名 */  let extName = '';  switch (file.type) {   case 'image/png':    extName = 'png';    break;   case 'image/x-png':    extName = 'png';    break;   case 'image/jpg':    extName = 'jpg';    break;   case 'image/jpeg':    extName = 'jpg';    break;  }  if(extName.length == 0) {   return res.send({'status': -1, 'msg': '只支持jpg和png格式圖片', result: ''});  }  /* 拼接新的文件名 */  let time = formatTime.format(new Date(), 'YYYYMMDDHHmmss');  let num = Math.floor(Math.random() * 8999 + 10000);  let imageName = `${time}_${num}.${extName}`;  let newPath = form.uploadDir + '/' + imageName;  /* 更改名字和路徑 */  fs.rename(file.path, newPath, (err) => {   if(err) {    return res.send({'status': -1, 'msg': '圖片上傳失敗', result: ''});   } else {    return res.send({'status': 200, 'msg': '圖片上傳成功', result: {url: `http://localhost:3000/serverImage/${imageName}`}});   }  }) })};            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 木兰县| 淮滨县| 大方县| 中超| 兖州市| 玛沁县| 清新县| 云霄县| 呈贡县| 含山县| 萨嘎县| 桑植县| 华亭县| 和硕县| 酉阳| 峨眉山市| 广南县| 厦门市| 河津市| 苍梧县| 大石桥市| 汽车| 焦作市| 手机| 大名县| 安阳市| 湖口县| 固原市| 九江县| 吉安市| 彭泽县| 白山市| 灌南县| 西乌珠穆沁旗| 荔波县| 上蔡县| 沁阳市| 沁阳市| 章丘市| 从化市| 嘉黎县|