Multer上传文件返回本地绝对路径致图片无法加载的问题
问题解答
部署到服务器后仍会存在问题
不管是本地还是服务器环境,直接存储本地绝对路径都会导致前端无法正常加载图片。浏览器出于安全策略,禁止直接访问本地文件系统路径(file://协议),必须通过服务器的HTTP接口来获取资源。服务器上的绝对路径对前端来说同样是不可访问的本地路径,因此这个问题不会随部署自动消失。
本地开发时的解决方法
需完成两个关键修改:
配置Express静态资源服务
在Express应用中添加静态资源中间件,让服务器对外提供uploads文件夹内的图片资源。根据你的代码结构(uploads位于src目录上级),在路由配置前添加以下代码:const express = require('express'); const path = require('path'); const app = express(); // 配置静态资源路由:访问/uploads/*时,映射到本地uploads文件夹 app.use('/uploads', express.static(path.join(__dirname, '..', 'uploads')));存储相对URL而非绝对路径
不要将req.file.path(本地绝对路径)存入数据库,改为存储可通过HTTP访问的相对URL。修改post路由中image字段的赋值逻辑:const plan = new Plan({ ...details, image: `/uploads/${req.file.filename}`, // 改用相对URL author: req.user._id, });
修改后,前端拿到的图片路径是类似/uploads/2022-12-05T12-39-35.924Z-Screenshot 2022-11-02 193712.png的HTTP可访问地址,浏览器会通过请求服务器获取图片,既解决本地开发问题,部署到服务器后也能正常工作(只要服务器同步配置静态资源服务且uploads路径正确)。
原始问题代码
const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, path.join(__dirname, "..", "uploads")); }, filename: function(req, file, cb) { const uniqueName = new Date().toISOString().replace(/:/g, "-") + "-" + file.originalname; cb(null, uniqueName); }, }); const fileFilter = function(req, file, cb) { if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) { return cb(new Error("Please upload an image file")); } cb(undefined, true); }; const upload = multer({ storage, limits: { fileSize: 1024 * 1024 * 5, // This number is in bytes, so this is 5mb }, fileFilter, }); // Post a new plan router.post("/plans", auth, upload.single("plan_image"), async(req, res) => { console.log("this is the file", req.file); const details = JSON.parse(req.body.details); console.log("this is the body", details); const plan = new Plan({ ...details, image: req.file.path, author: req.user._id, }); try { await plan.save(); res.status(201).send(plan); } catch (e) { console.log("failed to save", e); res.status(400).send(e); } });
内容的提问来源于stack exchange,提问作者Tsabary
相关产品推荐
相关产品推荐

