


Detailed explanation of Ajax and node.js multer to implement file upload function
As a node beginner, I have recently been working on a chat software that supports registration, login, online single and multi-person chat, emoticon sending, various file upload and download, adding and deleting friends, chat record saving, notification sound switch, background For image switching, games and other functions, the multer module was used. After various document searches and demo examples, I finally successfully implemented the single file upload function, which supports uploading of most file formats and displays it on the web page at the same time. This article mainly introduces Ajax cooperation. Node js multer implements the file upload function. Friends who need it can refer to it. I hope it can help everyone.
Effect
Does it feel like WeChat is instantly visible? Yes, it is based on the web version of WeChat.
To achieve the overall effect, it must be done with css and html. I am a front-end beginner and it is my first time to post a blog. I am really anxious. In the near future, I will put the code on github. Interested friends can take a look
Go directly to the code below, light abuse
Configuration
Installation
Install multer directly through the cmd command window
npm install multer -save
Server code
//引入http const http=require("http"); //引入express const express=require("express"); //引入multer const multer=require("multer"); //创建服务器,绑定监听端口 var app=express(); var server=http.createServer(app); server.listen(8081); //建立public文件夹,将HTML文件放入其中,允许访问 app.use(express.static("public")); //文件上传所需代码 //设置文件上传路径和文件命名 var storage = multer.diskStorage({ destination: function (req, file, cb){ //文件上传成功后会放入public下的upload文件夹 cb(null, './public/upload') }, filename: function (req, file, cb){ //设置文件的名字为其原本的名字,也可以添加其他字符,来区别相同文件,例如file.originalname+new Date().getTime();利用时间来区分 cb(null, file.originalname) } }); var upload = multer({ storage: storage }); //处理来自页面的ajax请求。single文件上传 app.post('/upload', upload.single('file'), function (req, res, next) { //拼接文件上传后的网络路径, var url = 'http://' + req.headers.host + '/upload/' + req.file.originalname; //将其发回客户端 res.json({ code : 1, data : url }); res.end(); });
Client code
nbsp;html> <meta> <title></title> <!--依托于jquery--> <script></script> <p> <label>file</label> <input> </p> <script> var file=$("#file")[0]; //这里使用的是onchange事件,所以当你选择完文件之后,就触发事件上传 file.onchange=function(){ //创建一个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"){ //只有满足以上格式时,才会触发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 网络路径,来实现上传文档的下载 if(formart=="docx"||formart=="txt"||formart=="doc"){ //结合css样式,实现显示图标 var className="docx"; //拼接html,生成到页面上去 var msg=`<a href="${src}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><i class="${className}">`; }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}">`; }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}">`; }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}">`; }else{ //所有的图片格式 msg=`<a href="javascript:;" rel="external nofollow" class="picCheck"><img src="/static/imghwm/default1.png" data-src="${src}" class="lazy" alt="Detailed explanation of Ajax and node.js multer to implement file upload function" >`; } // 这里将msg 追加到你要显示的区域 } } //不满足上传格式时 }else{ alert("文件格式不支持上传") } } </script>
Related recommendations:
multer definition and usage summary
Share using nodejs multer to implement file upload and download Example tutorial
Nodejs advanced: file upload example based on express+multer
The above is the detailed content of Detailed explanation of Ajax and node.js multer to implement file upload function. For more information, please follow other related articles on the PHP Chinese website!

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools
