ubuntu上安装(或者升级)nodejs,提供两个测试demo

1. 打开终端进行更新

sudo apt update

2. 安装npm

sudo apt install npm

3. 安装n

sudo npm install n -g

4. 通过n工具安装稳定版本nodejs

sudo n stable

5. 查看版本

node -v

提供两个demo文件

一个是app.js文件,文件名为app.js,提供了一个3000的端口号

const express = require('express');
const multer = require('multer');
const app = express();
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  },
});

const upload = multer({ storage: storage });
// const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res) => {
  console.log(req.file);
  res.send('File uploaded!');
});


// app.use(express.static('./uploads'));

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

一个是upload接口

const fs = require('fs');
const request = require('request');

const filePath = process.argv[2];
const uploadUrl = process.argv[3] || 'http://localhost:3000/upload';

if (!fs.existsSync(filePath)) {
  console.log('指定文件不存在');
  return
}

const formData = {
  file: fs.createReadStream(filePath),
};

request.post({ url: uploadUrl, formData: formData }, (err, res, body) => {
  if (err) {
    console.log('文件上传失败: ');
    console.error(err);
  } else {
    console.log('成功上传文件: ' + filePath);
  }
});

upload接口可以改写为python代码,文件名为platform_upload.py以下是上传自己的图片到本地,代码如下:

import os
import requests

# 上传的目标URL
url = 'http://localhost:3000/upload'

# 遍历文件夹中的所有图片文件
folder_path = '替换自己的文件夹'
for filename in os.listdir(folder_path):
    if filename.endswith('.jpg') or filename.endswith('.png'):
        # 构造文件路径
        file_path = os.path.join(folder_path, filename)
        # 读取文件内容
        with open(file_path, 'rb') as f:
            file_content = f.read()
        # 构造POST请求
        files = {'file': (filename, file_content)}
        response = requests.post(url, files=files)
        # 处理响应结果
        if response.status_code == 200:
            print('上传成功:', filename)
        else:
            print('上传失败:', filename)

对应文件夹下面,终端分别运行两个demo代码

node app.js
python3 platform_upload.py

如果本博客对你有用,记得点个赞哦!!