You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MEVN栈Heroku部署电影博客上传图片一段时间后消失问题求助

问题:Heroku部署的MEVN电影博客图片一段时间后消失

我用MEVN技术栈在Heroku上部署了一个电影博客网站。提交图片后初期能正常显示,但间隔1-2小时再访问时图片就消失了。

相关代码

API 创建文章代码

static async createPost(req,res){
    const post = req.body;
    const imagename = req.file.filename;
    post.image = imagename;
    try {
        await Post.create(post);
        res.status(201).json({message: 'Post created sucessfully!'})
    } catch (err) {
        res.status(400).json({message: err.message})
    }
}

Mongoose 模型

const mongoose = require("mongoose");

const postSchema = mongoose.Schema({
    title: String,
    category: String,
    content: String,
    image: String,
    created:{
        type: Date,
        default: Date.now
    }
});

module.exports = mongoose.model("Post", postSchema);

Vue 图片显示代码

<v-img height="250" :src="`/${post.image}`"></v-img>

控制台报错截图:
控制台截图

问题原因及解决办法

Heroku的临时文件系统是核心问题:Heroku的运行容器(dyno)会在闲置1小时左右自动休眠重启,或者在部署、资源调整时重启,重启后所有本地存储的文件都会被清空。你现在把图片存在服务器本地,数据库只存了文件名,容器重启后文件没了,自然显示不了。

解决办法就是放弃本地存储,改用专门的云存储服务,比如Cloudinary、AWS S3等,步骤如下:

  1. 注册并配置一个云存储服务,获取对应的API密钥
  2. 修改后端上传逻辑,将图片直接上传到云存储,把返回的图片完整URL存入MongoDB的image字段
  3. 前端直接使用这个URL作为图片的src,不需要拼接本地路径

举个Cloudinary的实现示例:

  • 安装依赖:
npm install cloudinary multer-storage-cloudinary multer
  • 配置Cloudinary和multer:
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');
const multer = require('multer');

cloudinary.config({
  cloud_name: '你的Cloudinary云名称',
  api_key: '你的API密钥',
  api_secret: '你的API密钥'
});

const storage = new CloudinaryStorage({
  cloudinary: cloudinary,
  params: {
    folder: 'movie-blog-images', // 云存储里的文件夹名
    allowed_formats: ['jpg', 'png', 'jpeg']
  }
});

const upload = multer({ storage: storage });
  • 修改createPost方法:
static async createPost(req,res){
    const post = req.body;
    // 直接使用Cloudinary返回的图片URL
    post.image = req.file.path;
    try {
        await Post.create(post);
        res.status(201).json({message: 'Post created sucessfully!'})
    } catch (err) {
        res.status(400).json({message: err.message})
    }
}
  • 前端调整图片显示:
<v-img height="250" :src="post.image"></v-img>

内容的提问来源于stack exchange,提问作者S M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:05:39