Home Web Front-end JS Tutorial Express+multer implements the specific steps to upload node images

Express+multer implements the specific steps to upload node images

Apr 12, 2018 pm 05:31 PM
node upload

This time I will bring you the specific steps for express multer to implement node image uploading. What are the precautions for express multer to implement node image uploading? The following is a practical case. Let’s take a look. .

The following will introduce how to use express multer to implement the image upload function in node. The specific content is as follows:

In the front end, we use ajax to asynchronously upload images, use file-input to upload images, use formdata objects to process image data, and post to the server

Use multermiddleware in node to process the upload routing interface

multer documentation

package.jsonhtml section

<body>
<p class="form-group">
    <label>File input:</label>
    <input type="file" name="file" id="file">
    <p id="result"></p>
    <img id="img" src="">
  </p>
  <button id="upload" class="btn btn-default">提交</button>
  </body>
Copy after login

js part

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  <script>
    //上传图片的业务逻辑函数
    function uploadFile(){
      //上传图片的input
      var file = document.getElementById("file")
      //因为准备用post提交,又因为图片的内容比较大,所以我们选择使用formdata来承载数据
      //创建formdata对象
      var formData = new FormData();
      //给formdata对象中放入数据(键值对的方式)
      formData.append('file',file.files[0]);
      //提交请求
      $.ajax({
        url: '/upload',//请求路径
        type: 'POST',
        data: formData,
        contentType: false,//为了让浏览器根据传入的formdata来判断contentType
        processData: false,//同上
        success: function(data){
          if(200 === data.code) {
            $('#result').html("上传成功!");
            $('#img').attr('src',data.data);
          } else {
            $('#result').html("上传失败!");
          }
          console.log(2)
        },
        error: function(){
          $("#result").html("与服务器通信发生错误");
        }
      });
      console.log(1)
    }
    //给按钮添加点击事件
    function postPage() {
        //上传按钮
        var uploada = document.getElementById('upload');
        uploada.addEventListener("click",function () {
          uploadFile();
        },false);
    }
    window.onload = function () {
      postPage();
    }
</script>
Copy after login

NodeJS logic code

const http = require('http')
const path = require('path')
const express = require('express')
//是nodejs中处理multipart/form-data数据格式(主要用在上传功能中)的中间件
//文档:https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md
const multer = require('multer')
const app = express()
//配置express的静态目录
app.use(express.static(path.join(dirname, 'public')));
app.get('/',(req,res)=>{
  res.sendFile(dirname+'/index.html')
})
//配置diskStorage来控制文件存储的位置以及文件名字等
var storage = multer.diskStorage({
  //确定图片存储的位置
  destination: function (req, file, cb){
    cb(null, './public/uploadImgs')
  },
![](http://images2017.cnblogs.com/blog/1283058/201802/1283058-20180201154342296-515041615.png)
  //确定图片存储时的名字,注意,如果使用原名,可能会造成再次上传同一张图片的时候的冲突
  filename: function (req, file, cb){
    cb(null, Date.now()+file.originalname)
  }
});
//生成的专门处理上传的一个工具,可以传入storage、limits等配置
var upload = multer({storage: storage});
//接收上传图片请求的接口
app.post('/upload', upload.single('file'), function (req, res, next) {
  //图片已经被放入到服务器里,且req也已经被upload中间件给处理好了(加上了file等信息)
  //线上的也就是服务器中的图片的绝对地址
  var url = '/uploadImgs/' + req.file.filename
  res.json({
    code : 200,
    data : url
  })
});
http.createServer(app).listen(3000,()=>{
  console.log('server is listening')
})
Copy after login

I feel good about myself, but I don’t know why the blog park wants to remove the homepage for me....

再发一次,if(delete){
alert('Never publish anything again.')
}else{
alert(1)
}
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting content, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of cookie usage in Django

How to replace url parameters with regular JS

The above is the detailed content of Express+multer implements the specific steps to upload node images. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement file upload and processing in FastAPI How to implement file upload and processing in FastAPI Jul 28, 2023 pm 03:01 PM

How to implement file upload and processing in FastAPI FastAPI is a modern, high-performance web framework that is easy to use and powerful. It provides native support for file upload and processing. In this article, we will learn how to implement file upload and processing functions in the FastAPI framework, and provide code examples to illustrate specific implementation steps. First, we need to import the required libraries and modules: fromfastapiimportFastAPI,UploadF

How to delete node in nvm How to delete node in nvm Dec 29, 2022 am 10:07 AM

How to delete node with nvm: 1. Download "nvm-setup.zip" and install it on the C drive; 2. Configure environment variables and check the version number through the "nvm -v" command; 3. Use the "nvm install" command Install node; 4. Delete the installed node through the "nvm uninstall" command.

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

How to solve the problem of slow upload speed on Win10 computer How to solve the problem of slow upload speed on Win10 computer Jul 01, 2023 am 11:25 AM

How to solve the slow upload speed of Win10 computer? When we use the computer, we may feel that the file upload speed of our computer is very slow. So what is the situation? In fact, this is because the default upload speed of the computer is 20%, so the upload speed is very slow. Many friends do not know how to operate in detail. The editor has compiled the steps to format the C drive in Win11 below. If you are interested, follow Let’s take a look below! Solution to the slow upload speed of Win10 1. Press win+R to call up run, enter gpedit.msc, and press Enter. 2. Select the management template, click Network--Qos Packet Scheduler, and double-click Limit to reserve bandwidth. 3. Select Enabled, which will bring

How to upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

See all articles