简体   繁体   中英

Sending Files from frontend to backend(MySql) using Nodejs

I have sent files from frontend to backend using nodejs saved in a folder called uploads.Now I want to send files to database(MySql). What should I do? Whether I have to use sql queries also want to know how to create a table for the same. What type column should I include My Nodejs code is below:

const express = require("express");
const path = require("path");
const multer = require("multer");
const app = express();
const cors = require("cors");

const corsOptions = {
  origin: "*",
};

app.use(cors(corsOptions));

app.post("/uploads", function (req, res, next) {
  upload(req, res, function (err) {
    if (err) {
      res.send({ result: "failed" });
    } else {
      res.send({ result: "Success" });
    }
  });
});

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/fileupload.html");
});

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads");
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname);
  },
});

// filesize i.e. 1 MB. it is optional
const maxSize = 1 * 1000 * 1000;
// Function to serve all static files
// inside public directory.
app.use(express.static("/nodejs-mysql"));
app.use("/uploads", express.static("uploads"));

var upload = multer({
  storage: storage,
  limits: { fileSize: maxSize },
}).single("myFile");

app.listen(5000, () => console.log("Its working on port 500

0")) my HTML code is below

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
</head>

<body>
    <h1>File Upload</h1>
     
        <input type="file" name="file" id="fileUpload">
        <button onclick="fileUpload()">submit</button>
   
    <script>
        function fileUpload()  {
        
           var input = document.querySelector('input[type="file"]')
               
            const formData = new FormData()
            formData.append('myFile', input.files[0])
               console.log(formData);
            fetch('http://localhost:5000/uploads', {
                method: 'POST',
                body: formData
                })
                .then(response => response.json())
                .then(data => {
                    console.log(data)
                })
                .catch(error => {
                    console.error(error)
                })
        }
    </script>
</body>

</html>

You must save the name and address of the file uploaded to the server in the database and deliver the same saved address to the user.

const insertData = "INSERT INTO users_file(file_src)VALUES(?)"
    db.query(insertData, [imgsrc], (err, result) => {
        if (err) throw err
        console.log("file uploaded")
    })

and then res.send(http://127.0.0.1:3000/images/' + req.file.filename)

If you want save image to db (I don't recommend) you should have a BLOB type in database also you can read this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM