当前位置: 首页 > 工具软件 > WebDAV.js > 使用案例 >

Web上实现文件上传的几种方式(原生/Antd+Node.js实现)

汪甫
2023-12-01

一、FormData+express:

index.html:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>multer的使用方案</title>
</head>

<body>
    <input type="file" id="file1" /><input type="button" value="submit" id="submit-button" />

    <script>
        document.getElementById("submit-button").onclick = function () {
            const fileObj = document.getElementById("file1").files[0]; // 获取文件对象

            const URL = "/api/upload"; // 接收上传文件的后台地址 
            // FormData 对象
            const form = new FormData();
            form.append("author", "samve"); // 可以增加表单数据
            form.append("file", fileObj); // 文件对象
            // XMLHttpRequest 对象
            const xhr = new XMLHttpRequest();
            xhr.open("post", URL, true);
            xhr.onload = function () {
                alert("上传完成!");
            };
            xhr.send(form);
    }
    </script>

</body>

</html>

upload.js:

const express = require("express")
const fs = require("fs")
const app = express();

app.engine("html", require("express-art-template"))

// 核心begin //
var multer = require('multer');//获得中间件
var upload = multer({dest:'./uploads/'});//指定配置项,这里指定文件保存于当前目录下的upload子目录
app.use(upload.any()); // 通过这个注册
// 核心end //

// 渲染页面
app.get("/index", (req, res) => {
    res.render("index.html");
})

app.post("/api/upload", upload.single('任意名称'), (req, res) => {
    console.log("文件上传信息:");
    console.log(req.files);  // 上传的文件信息
 
   var des_file = __dirname + "/uploads/" + req.files[0].originalname; //文件名
   fs.readFile( req.files[0].path, function (err, data) {  // 异步读取文件内容
        fs.writeFile(des_file, data, function (err) { // des_file是文件名,data,文件数据,异步写入到文件
         if( err ){
              console.log( err );
         }else{
               // 文件上传成功,respones给客户端
               response = {
                   message:'File uploaded successfully', 
                   filename:req.files[0].originalname
              };
          }
          console.log( response );
          res.jsonp(  response );
       });
   });
})

app.listen(5555, () => {
    console.log("服务启动成功......");
})

const express = require("express")
const fs = require("fs")
const path = require("path")
const app = express();

const bodyParser = require("body-parser");
app.use("/static/", express.static("./static/"));
app.use('/node_modules/', express.static('./node_modules/'));

// 告诉express框架使用什么模板引擎渲染什么后缀的模板文件
app.engine("html", require("express-art-template"))

// 2. 告诉express框架模板存放的位置是什么
// 第一个views是固定的,是express的配置项名字,告诉express框架模板存放的位置
// 第二个views是文件夹的名字
app.set('views', path.join(__dirname, 'views'))
// 3. 告诉express框架模板的默认后缀是什么 ( 方便在渲染模板的时候,省去后缀 )
app.set('view engine', 'html');

app.use(bodyParser.urlencoded({ extended: false }))

// 核心begin //
var multer = require('multer');//获得中间件

// 通过 filename 属性定制
// var storage = multer.diskStorage({
//     destination: path.resolve(__dirname, './uploads/'),
//     filename: function (req, file, cb) {
//         cb(null, file.fieldname + '-' + Date.now());
//     }
// });

// var storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         cb(null, path.resolve(__dirname, ));    // 保存的路径,备注:需要自己创建
//     },
//     filename: function (req, file, cb) {
//         cb(null, file.fieldname + '-' + Date.now());
//     }
// });

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/');    // 保存的路径,备注:需要自己创建
    },
    filename: function (req, file, cb) {
        console.log(file);
        cb(null, file.originalname);
    }
});

// 通过 storage 选项来对 上传行为 进行定制化
var upload = multer({ storage: storage })

app.use(upload.any()); // 通过这个注册

// 渲染页面
app.get("/index", (req, res) => {
    res.render("index.html");
})

app.post("/api/upload", upload.single('file_1'), (req, res) => {

})

app.listen(7777, () => {
    console.log("服务启动成功......");
})

 package.json:

{
  "name": "node1",
  "version": "1.0.0",
  "description": "",
  "main": "b.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "art-template": "^4.13.2",
    "body-parser": "^1.19.0",
    "cookie-parser": "^1.4.5",
    "express": "^4.17.1",
    "express-art-template": "^1.0.1",
    "multer": "^1.4.2",
    "mysql": "^2.18.1"
  }
}

二、Antd 3.x+express:

import React, { Component } from 'react';
import { Upload, Button, Icon, message, Progress } from 'antd'

class UploadComponent extends Component {
  state = {
    progress: 0
  }

  render() {
    const _this = this;

    const props = {
      name: 'file',
      action: 'http://localhost:3000/api/upload',
      headers: {
        authorization: 'authorization-text',
      },
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} file uploaded successfully`);
          console.log(info.file);
          _this.setState({
            progress: info.file.percent
          });
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    };

    return (
      <>
        <Upload {...props}>
          <Button>
            <Icon type="upload" /> Click to Upload</Button>
        </Upload>
        <Progress percent={this.state.progress} />
      </>

    );
  }
}

export default App;

package.json:

{
  "name": "spug_web",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@antv/data-set": "^0.10.2",
    "ace-builds": "^1.4.7",
    "antd": "^3.25.0",
    "axios": "^0.21.1",
    "bizcharts": "^3.5.6",
    "history": "^4.10.1",
    "http-proxy-middleware": "^0.20.0",
    "lodash": "^4.17.19",
    "mobx": "^5.15.0",
    "mobx-react": "^6.1.4",
    "moment": "^2.24.0",
    "react": "^16.11.0",
    "react-ace": "^8.0.0",
    "react-dom": "^16.11.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.2.0",
    "wangeditor": "^4.6.15",
    "xterm": "^4.6.0",
    "xterm-addon-fit": "^0.4.0"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "GENERATE_SOURCEMAP=false react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:5555",
  "devDependencies": {
    "@babel/plugin-proposal-decorators": "^7.7.0",
    "babel-plugin-import": "^1.12.2",
    "customize-cra": "^0.8.0",
    "react-app-rewired": "^2.1.5"
  }
}

express代码同上。

Multer官方地址:

https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md

 类似资料: