Home > Web Front-end > JS Tutorial > body text

How to use multer upload

php中世界最好的语言
Release: 2018-04-16 11:43:18
Original
1389 people have browsed it

This time I will show you how to use multer upload, what are the precautions when using multer upload, the following is a practical case, let's take a look.

There are still quite a lot of gains, mainly due to some details of using wenpack. It is 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.

As 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. I followed the official website to find updated places bit by bit.

What I currently find useful are: 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, only 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.

Put 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')
Copy after login
<!-- 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="" alt="" id="img" width="40" height="40">
  <script>
    let file = document.getElementById('file');
    file.onchange = function (e) {
      let file = e.target.files[0];
      let xhr = new XMLHttpRequest();
      let fd = new FormData();
      fd.append('myfile', file)
      xhr.open('post', '/public/index.html')
      xhr.onload = function () {
        // console.log(xhr)
        if (xhr.status === 200) {
          let data = JSON.parse(xhr.responseText)
          document.getElementById('result').innerHTML = this.response
          document.getElementById('img').src = data.filename
        }
      }
      xhr.send(fd)
    }
  </script>
</body>
</html>
Copy after login

I don’t want to reference the jquery library, so I wrote native ajax. Generally speaking, 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 in, 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: 'public/' })
Copy after login

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)
Copy after login

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

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 })
Copy after login

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

filename: function (req, file, cb) {
 cb(null, file.fieldname + '.png');
}
Copy after login

You will find that the name of each picture you pass in is myfile.png, and 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. ​ ​

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

Recommended reading:

Detailed explanation of the use of BootStrap's text editor component Summernote

##Operation search component is displayed on the keyboard

jquery submits array data using springmvc receiving method

The above is the detailed content of How to use multer upload. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!