search
HomeWeb Front-endJS TutorialDetailed explanation of uploading and using Express multer
Detailed explanation of uploading and using Express multerJan 20, 2018 am 10:30 AM
expressDetailed explanation

This article mainly introduces the use of multer upload in the Express series. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

I have been reading "The Definitive Guide to NodeJS" for the past two days. I have read this book for a long time, but I have never read it carefully. I just read it carefully this time.

I gained a lot, mainly in the details of using wenpack. It was a bit of an epiphany experience. In addition, I am no longer confused on node. But to be honest, it is quite difficult to do something directly using node at the current level. Today I tested the link to mongodb and mysql database. Although it can be used, it is still weird. So I want to use the existing framework first, and then learn node backwards.

For the framework, I chose express.

The main thing is to test the middleware mentioned in several books. It was written a little early, and many APIs are outdated. Just follow the official website. Look for an updated place.

What I currently find useful is: multer and static.

The latter can debug the page locally, which is especially useful for mobile pages.

This time I will mainly talk about multer. I have not implemented all the functions. I only implemented the function of uploading a single image, and I will explore the others.

This is the entire directory of files, there are two main ones, one is main.js in the root directory, and the other is public/index.html.

Place the code:


//main.js
let express = require('express');

var multer = require('multer')

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
   cb(null, 'public/');
  },
  filename: function (req, file, cb) {
   cb(null, Date.now() + '.png');
  }
 })
 
var upload = multer({ storage: storage })

//var upload = multer({ dest: 'public/' })
 

let app = express()

app.use(express.static('public'))

app.post('/public/index.html',upload.single('myfile'),(req,res,next)=>{
  console.log(req.file)
  res.send(req.file)
})

app.listen(3300,'127.0.0.1')


<!-- index.html -->

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <input type="file" id="file" accept="image/*">
  <p id="result"></p>
  <img src="/static/imghwm/default1.png"  data-src="" alt="  class="lazy"   alt="" id="img"    style="max-width:90%"  style="max-width:90%">
  <script>
    let file = document.getElementById(&#39;file&#39;);
    file.onchange = function (e) {
      let file = e.target.files[0];
      let xhr = new XMLHttpRequest();
      let fd = new FormData();
      fd.append(&#39;myfile&#39;, file)
      xhr.open(&#39;post&#39;, &#39;/public/index.html&#39;)
      xhr.onload = function () {
        // console.log(xhr)
        if (xhr.status === 200) {
          let data = JSON.parse(xhr.responseText)
          document.getElementById(&#39;result&#39;).innerHTML = this.response
          document.getElementById(&#39;img&#39;).src = data.filename
        }
      }
      xhr.send(fd)
    }
  </script>
</body>

</html>

I don’t want to reference the jquery library, so I wrote ajax natively. It shouldn't be difficult. In short, after clicking the button to select the image, the image information will be placed in an object with the key name myfile and passed to the background.

express stores the received pictures in the /public/ file. There is a small pitfall here. You can see that I commented this line of code in main.js:


var upload = multer({ dest: &#39;public/&#39; })

In fact, I used this line of code at the beginning,dest means to choose a path to store the file, but there is a small problem with writing it this way. The saved file does not have a suffix.

When I return data to the front desk


res.send(req.file)

This problem is very serious. For example, in one scenario, I upload a picture as an avatar, but when I wait Next time I enter my personal page, the data returned to me by the background cannot be used as the address of the image, which is very troublesome. So I found a reason on the Internet and replaced the above code comment with this:


var storage = multer.diskStorage({
  destination: function (req, file, cb) {
   cb(null, &#39;public/&#39;);
  },
  filename: function (req, file, cb) {
   cb(null, Date.now() + &#39;.png&#39;);
  }
})

var upload = multer({ storage: storage })

destination is the address where the file is stored, filename is set to the name of the file, so if it is written like this:


filename: function (req, file, cb) {
 cb(null, file.fieldname + &#39;.png&#39;);
}

you will find that the name of each picture you pass in is It is myfile.png, the new one overwrites the old one. So in order to save all the pictures passed in, I use Date.now() as a different identifier for each picture, so that there will be no overwriting.

That’s it for now, I’ll update it next time I upload more pictures.

Related recommendations:

Detailed explanation of Ajax and node.js multer to implement file upload function

multer definition and Usage summary

Nodejs advanced: file upload example based on express+multer

The above is the detailed content of Detailed explanation of uploading and using Express multer. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
node项目中如何使用express来处理文件的上传node项目中如何使用express来处理文件的上传Mar 28, 2023 pm 07:28 PM

怎么处理文件上传?下面本篇文章给大家介绍一下node项目中如何使用express来处理文件的上传,希望对大家有所帮助!

Django框架中的缓存机制详解Django框架中的缓存机制详解Jun 18, 2023 pm 01:14 PM

在Web应用程序中,缓存通常是用来优化性能的重要手段。Django作为一款著名的Web框架,自然也提供了完善的缓存机制来帮助开发者进一步提高应用程序的性能。本文将对Django框架中的缓存机制进行详解,包括缓存的使用场景、建议的缓存策略、缓存的实现方式和使用方法等方面。希望对Django开发者或对缓存机制感兴趣的读者有所帮助。一、缓存的使用场景缓存的使用场景

php-fpm调优方法详解php-fpm调优方法详解Jul 08, 2023 pm 04:31 PM

PHP-FPM是一种常用的PHP进程管理器,用于提供更好的PHP性能和稳定性。然而,在高负载环境下,PHP-FPM的默认配置可能无法满足需求,因此我们需要对其进行调优。本文将详细介绍PHP-FPM的调优方法,并给出一些代码示例。一、增加进程数默认情况下,PHP-FPM只启动少量的进程来处理请求。在高负载环境下,我们可以通过增加进程数来提高PHP-FPM的并发

PHP function_exists()函数用法详解PHP function_exists()函数用法详解Jun 27, 2023 am 10:32 AM

在PHP开发中,有时我们需要判断某个函数是否可用,这时我们便可以使用function_exists()函数。本文将详细介绍function_exists()函数的用法。一、什么是function_exists()函数?function_exists()函数是PHP自带的一个内置函数,用于判断某个函数是否被定义。该函数返回一个布尔值,如果函数存在返回True,

Gin框架的模板渲染功能详解Gin框架的模板渲染功能详解Jun 22, 2023 pm 10:37 PM

Gin框架是目前非常流行的Go语言Web框架之一。作为一个轻量级的框架,Gin提供了丰富的功能和灵活的架构,使得它在Web开发领域中备受欢迎。其中一个特别重要的功能是模板渲染。在本文中,我们将介绍Gin框架的模板渲染功能,并深入了解它的实现原理。一、Gin框架的模板渲染功能Gin框架使用了多种模板渲染引擎来构建Web应用程序。目前,它支持以下几种模板引擎:

深入比较Express和Laravel:如何选择最佳框架?深入比较Express和Laravel:如何选择最佳框架?Mar 09, 2024 pm 01:33 PM

深入比较Express和Laravel:如何选择最佳框架?在选择一个适合自己项目的后端框架时,Express和Laravel无疑是两个备受开发者欢迎的选择。Express是基于Node.js的轻量级框架,而Laravel则是基于PHP的流行框架。本文将深入比较这两个框架的优缺点,并提供具体的代码示例,以帮助开发者选择最适合自己需求的框架。性能和扩展性Expr

PHP中的ORM框架使用详解PHP中的ORM框架使用详解Jun 23, 2023 am 11:22 AM

ORM(Object-RelationalMapping)框架是一种用于将面向对象编程语言中的对象模型与关系型数据库之间映射的技术。它使开发人员能够使用面向对象的方式操作数据库,而不需要直接操作SQL语言。在PHP开发领域中,ORM框架也得到了广泛的应用。本文将详细介绍PHP中的ORM框架使用方法。一、ORM框架的优点使用ORM框架有以下优点:1.提高开发

PHP strpos()函数用法详解PHP strpos()函数用法详解Jun 27, 2023 am 10:43 AM

PHPstrpos()函数用法详解在PHP编程中,字符串处理是非常重要的一部分。PHP通过提供一些内置函数来实现字符串处理。其中,strpos()函数就是PHP中最常用的一个字符串函数之一。该函数的目的是在一个指定的字符串中搜索另一个指定字符串的位置,如果包含则返回这个位置,否则返回false。本文将通过详细分析PHPstrpos()函数的用法,助你更好

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.