node_express framework 03 + formidable to realize file upload and user access

Requirements: Users upload files, and users can easily access the uploaded files

1. Use the framework to create a good project structure:

node_express03_Scaffolding Express-generator_You Xiaobei's Blog-CSDN Blog

If not, refer to the blog above, which introduces the scaffolding and directory structure of express.

2. Responsive html file allows users to upload files

In fact, it is to respond to an ejs file to the user. The ejs file is as follows:

Note: the attribute must be added to the form tag: enctype="multipart/form-data", and then the input tag also needs to set the name attribute.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>上传</title>
  </head>
  <body>
    <!-- 必须加上 enctype="multipart/form-data" -->
    <form action="/upload" method="post" enctype="multipart/form-data">
      <!-- type、name 属性必填 -->
      头像上传:<input type="file" name="upload" />
      <button>提交</button>
    </form>
  </body>
</html>

3. Receive and save the file formidable

formidable is a package that is very suitable for handling file uploads, https://www.npmjs.com/package/formidable

download: 

npm i formidable

import:

const formidable = require("formidable");

Use: We need to set the save path of the file in the formidable function, and the option to retain the suffix. Save uploaded culture can be implemented.

var express = require("express");
var router = express.Router();
// 导入依赖
const formidable = require("formidable");

// 虽然 写的是 根路径,但实际访问的是 /upload 路径,如果 写了 /api ,那就是 /upload/api
router.post("/", function (req, res, next) {
  // 创建 form 对象
  const form = formidable({
    multiples: true,
    // 保存上传的文件的路径
    uploadDir: __dirname + "/../public/images",
    // 保留后缀
    keepExtensions: true,
  });
  // 解析请求报文
  form.parse(req, (err, fields, files) => {
    if (err) {
      next(err);
      return;
    }
    console.log(files); // 包含需要的 newFilename 新文件名
    res.send("ok");
  });
});

module.exports = router;

4. Send to user

We give the address of the file to the user so that the user can easily access it. We need to record the storage path of resources, but we cannot fully record the entire path, taking into account changes in the domain name and port of the server. We just save the path from the root directory to the image.

 // 保存资源路径,前面省略的路径是 /public,这是资源路径,不用写
    const url = "/images/" + files.upload.newFilename;
    res.send("资源路径为" + url);

 

Guess you like

Origin blog.csdn.net/m0_66492535/article/details/129914590