簡體   English   中英

如何在服務器上將圖像保存為 URL?

[英]How can I save an image on the server as a URL?

編輯

我刪除app.use(fileUpload()); . 所以它終於奏效了。 但不幸的是,在backend的文件夾images中,我只得到這些文件c43jnfeh734hdfudf

因此,前端不顯示任何內容。

const imagePath = req.file.path
const description = req.file.originalname

console.log(imagePath)
console.log(description)
images\c43jnfeh734hdfudf
empty

我有個問題。 我想在我的服務器上保存帶有固定 URL 的圖像。 我找到了以下代碼片段,但不幸的是它不起作用。 我在后端收到以下錯誤: 'TypeError: Cannot read property 'path' of undefined'

以下值為'undefined' const imagePath = req.file.path const description = req.body.description如何在服務器上將圖像保存為 URL?

這是教程,我在其中找到了代碼片段https://github.com/meech-ward/sammeechward.com_mdx/blob/master/content/articles/uploading-images-express-and-react/index.mdx

反應

import { useState } from 'react'
import axios from 'axios'

export default function App() {
  const [file, setFile] = useState()
  const [description, setDescription] = useState("")
  const [image, setImage] = useState()

  const submit = async event => {
    event.preventDefault()

    const formData = new FormData()
    formData.append("image", file)
    formData.append("description", description)

    const result = await axios.post('/api/images', formData, { headers: {'Content-Type': 'multipart/form-data'}})
    setImage(result.data.imagePath)
  }

  return (
    <div className="App">
      <form onSubmit={submit}>
        <input
          filename={file} 
          onChange={e => setFile(e.target.files[0])} 
          type="file" 
          accept="image/*"
        ></input>
        <input
          onChange={e => setDescription(e.target.value)} 
          type="text"
        ></input>
        <button type="submit">Submit</button>
      </form>
      { image && <img src={image}/>}
    </div>
  )
}

后端

const express = require('express')
const fs = require('fs')
const multer = require('multer')

const upload = multer({ dest: 'images/' })

const app = express()

// app.use('/images', express.static('images'))
app.get('/images/:imageName', (req, res) => {
  // do a bunch of if statements to make sure the user is 
  // authorized to view this image, then

  const imageName = req.params.imageName
  const readStream = fs.createReadStream(`images/${imageName}`)
  readStream.pipe(res)
})

app.post('/api/images', upload.single('image'), (req, res) => {
  const imagePath = req.file.path
  const description = req.body.description

  // Save this data to a database probably

  console.log(description, imagePath)
  res.send({description, imagePath})
})

app.listen(8080, () => console.log("listening on port 8080"))

路線/Test.js

const express = require("express");
const router = express.Router();
module.exports = router;
const auth_util = require("../utilities/auth_util");
const pgclient = require("../app");
const multer = require('multer')
const upload = multer({ dest: 'images/' })

// app.use('/images', express.static('images'))
router.get('/images/:imageName', (req, res) => {
  // do a bunch of if statements to make sure the user is 
  // authorized to view this image, then

  const imageName = req.params.imageName
  const readStream = fs.createReadStream(`images/${imageName}`)
  readStream.pipe(res)
})

router.post('/api/images', upload.single('image'), (req, res) => {
  console.log(req.file)
  console.log(req.files)
  const imagePath = req.file.path
  const description = req.body.description

  // Save this data to a database probably

  console.log(description, imagePath)
  res.send({ description, imagePath })
})

// added the lines below
const path = require("path");

router.use(express.static(path.join(__dirname, 'build')));

router.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

應用程序.js

const express = require("express");
const cors = require("cors");
//const fileUpload = require("express-fileupload");
const session = require("express-session");
const { Pool } = require("pg");



const app = express();

app.use(express.json());
//app.use(fileUpload());
//------------------------------CORS settings------------------------------
var whitelist = [
    "http://localhost:3000",
    "http://localhost:3001",
];
var corsOptions = {
    credentials: true,
    exposedHeaders: ["set-cookie"],
    origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1 || !origin) {
            callback(null, true);
        } else {
            // callback(null, true)
            callback(new Error("Not allowed by CORS!!"));
        }
    },
};
app.options("*", cors(corsOptions));

const pgclient = new Pool({
    user: process.env.DB_USER,
    host: process.env.DB_HOST,
    database: process.env.DB_DATABASE,
    password: process.env.DB_PASSWORD,
    port: process.env.DB_PORT,
});

module.exports = pgclient;


app.set("trust proxy", 1);


const testRoute = require("./routes/test");
app.use("/test", cors(corsOptions), testRoute);

app.get("/", cors(corsOptions), (req, res, next) => {
    res.send("Welcome");
});

module.exports = app;

首先,您需要刪除express-fileupload 無需將它與multer一起使用。

要在指定文件夾中擁有帶擴展名的正確文件,您需要更改這部分代碼:

刪除此行:

const upload = multer({ dest: 'images/' })

將其更改為:

// routes/Test.js

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'images')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})

const upload = multer({ storage: storage })

對於防止覆蓋相同文件名的常規和標准方法,您需要將filename名更改為:

filename: function (req, file, cb) {
    cb(null, `${Date.now()}-${file.originalname}`)
}

根據這個答案,multer 在其文件上傳中使用了一種 cookie,而 cookie 的過時版本會導致文件上傳失敗。 嘗試清除瀏覽器的 cookies。

multer - req.file 始終未定義

編輯:這是在我這邊用一些圖片工作的腳本: 在此處輸入圖像描述

我確實需要做一個小的編輯才能讓這個例子在 chrome 上運行。 為了避免 CORS 策略,前端和后端必須都托管在同一個端口。 因此,我添加了獲取路由以從 expressjs 服務器靜態提供反應頁面:

const express = require('express')
const fs = require('fs')
const multer = require('multer')

const upload = multer({ dest: 'images/' })

const app = express()

// app.use('/images', express.static('images'))
app.get('/images/:imageName', (req, res) => {
    // do a bunch of if statements to make sure the user is 
    // authorized to view this image, then

    const imageName = req.params.imageName
    const readStream = fs.createReadStream(`images/${imageName}`)
    readStream.pipe(res)
})

app.post('/api/images', upload.single('image'), (req, res) => {
    console.log(req.file)
    console.log(req.files)
    const imagePath = req.file.path
    const description = req.body.description

    // Save this data to a database probably

    console.log(description, imagePath)
    res.send({ description, imagePath })
})

// added the lines below
const path = require("path");

app.use(express.static(path.join(__dirname, 'build')));

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(8080, () => console.log("listening on port 8080"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM