溫馨提示×

溫馨提示×

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

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

Ajax如何配合node.js multer實現(xiàn)文件上傳功能

發(fā)布時間:2021-05-21 13:57:55 來源:億速云 閱讀:196 作者:小新 欄目:web開發(fā)

小編給大家分享一下Ajax如何配合node.js multer實現(xiàn)文件上傳功能,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

說明

作為一個node 初學(xué)者,最近在做一個聊天軟件,支持注冊、登錄、在線單人、多人聊天、表情發(fā)送、各種文件上傳下載、增刪好友、聊天記錄保存、通知聲開關(guān)、背景圖片切換、游戲等功能,所以用到了multer 模塊,經(jīng)過各種查文檔,做demo例子,終于成功實現(xiàn)單個文件上傳功能,支持大部分文件格式上傳,同時顯示到網(wǎng)頁上

效果

是不是有種微信即視感,沒錯,就是根據(jù)網(wǎng)頁版微信來做的,

Ajax如何配合node.js multer實現(xiàn)文件上傳功能

要實現(xiàn)整體效果的話,要配合css和html來做,前端初學(xué)者,第一次發(fā)博客,實在捉急,近期,將會將代碼放到github上去,感興趣的朋友可以去看一下

下面直接上代碼,輕虐

配置

安裝

直接通過cmd命令窗口安裝multer

npm install multer -save

服務(wù)器代碼

//引入http
const http=require("http");
//引入express
const express=require("express");
//引入multer
const multer=require("multer");
//創(chuàng)建服務(wù)器,綁定監(jiān)聽端口
var app=express();
var server=http.createServer(app);
server.listen(8081);
//建立public文件夾,將HTML文件放入其中,允許訪問
app.use(express.static("public"));
//文件上傳所需代碼
//設(shè)置文件上傳路徑和文件命名
var storage = multer.diskStorage({
  destination: function (req, file, cb){
    //文件上傳成功后會放入public下的upload文件夾
    cb(null, './public/upload')
  },
  filename: function (req, file, cb){
    //設(shè)置文件的名字為其原本的名字,也可以添加其他字符,來區(qū)別相同文件,例如file.originalname+new Date().getTime();利用時間來區(qū)分
    cb(null, file.originalname)
  }
});
var upload = multer({
  storage: storage
});
//處理來自頁面的ajax請求。single文件上傳
app.post('/upload', upload.single('file'), function (req, res, next) {
  //拼接文件上傳后的網(wǎng)絡(luò)路徑,
  var url = 'http://' + req.headers.host + '/upload/' + req.file.originalname;
  //將其發(fā)回客戶端
  res.json({
    code : 1,
    data : url
  });
  res.end();
});

客戶端代碼

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <!--依托于jquery-->
  <script src="js/jquery-1.11.3.js"></script>
</head>
<body>
  <div class="container">
    <label>file</label>
    <input type="file" name="file" id="file">
  </div>
<script>
      var file=$("#file")[0];
      //這里使用的是onchange事件,所以當(dāng)你選擇完文件之后,就觸發(fā)事件上傳
      file.onchange=function(){
        //創(chuàng)建一個FormDate
        var formData=new FormData();
        //將文件信息追加到其中
        formData.append('file',file.files[0]);
        //利用split切割,拿到上傳文件的格式
        var src=file.files[0].name,
            formart=src.split(".")[1]; 
        //使用if判斷上傳文件格式是否符合                                                          
                                                              if(formart=="jpg"||formart=="png"||
        formart=="docx"||formart=="txt"||
        formart=="ppt"||formart=="xlsx"||
        formart=="zip"||formart=="rar"||
        formart=="doc"){
        //只有滿足以上格式時,才會觸發(fā)ajax請求
          $.ajax({
            url: '/upload',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function(data){
            //上傳成功之后,返回對象data         
              if(data.code>0){
                var src=data.data;
                    //利用返回值src 網(wǎng)絡(luò)路徑,來實現(xiàn)上傳文檔的下載    
                    if(formart=="docx"||formart=="txt"||formart=="doc"){
                    //結(jié)合css樣式,實現(xiàn)顯示圖標(biāo)
                  var className="docx";
                    //拼接html,生成到頁面上去  
                  var msg=`<a href="${src}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><i class="${className}"></i></a>`;
                }else if(formart=="ppt"){
            //PPT 格式
                    className="ppt";
                  msg=`<a href="${src}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><i class="${className}"></i></a>`;
                }else if(formart=="xlsx"){
            //xlsx 格式
                    className="xlsx";
                  msg=`<a href="${src}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><i class="${className}"></i></a>`;
          }else if(formart=="zip"||formart=="rar"){
          //zip || rar 格式
                    className="zip";
                  msg=`<a href="${src}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><i class="${className}"></i></a>`;
                }else{
          //所有的圖片格式      
                  msg=`<a href="javascript:;" rel="external nofollow" class="picCheck"><img src="${src}"></a>`;
                }
                // 這里將msg 追加到你要顯示的區(qū)域 
              }
            } 
         //不滿足上傳格式時 
        }else{
          alert("文件格式不支持上傳")
        }
      }
</script>
</body>
</html>

什么是ajax

ajax是一種在無需重新加載整個網(wǎng)頁的情況下,能夠更新部分網(wǎng)頁的技術(shù),可以通過在后臺與服務(wù)器進行少量數(shù)據(jù)交換,使網(wǎng)頁實現(xiàn)異步更新。

看完了這篇文章,相信你對“Ajax如何配合node.js multer實現(xiàn)文件上傳功能”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

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

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

AI