اذهب إلى المحتوى
  • 0

مشكلة الصور في mongodb

Ahmed Zehry

السؤال

لدي نموذج في قاعدة بيانات mongo  هذا هو 

/**
 * Module dependencies.
 */
const mongoose = require("mongoose");
/**
 * Schema definition
 */

const ModelSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
    },
    pathname:{
      type: String,
      required: true,
      unique: true,
    },
    title: {
      type: String,
      unique: true,
      default: function() {
        return this.name;
      }
    },
    desc: {
      type: Array,
      required: true,
      default:[""]
    },
    image: {
       data: Buffer, 
      contentType:String  
    },
  },
  {
    timestamps: true,
  }
);

ModelSchema.set("toJSON", {
  virtuals: true,
  versionKey: false,
  transform: (doc, ret) => {
    delete ret._id;
  },
});

const Model = mongoose.model("MainCategory", ModelSchema);

module.exports = Model;

اريد ارسال الصور له عبر صفحة react 

import React, { useEffect, useState } from 'react'
import { AppFooter, AppHeader, AppSidebar, DocsExample } from '../../../components'
import axios from 'axios'
import { CButton, CForm, CFormInput, CFormLabel, CFormTextarea } from '@coreui/react'
export default function programs() {
  const [name, setname] = useState('')
  const [image, setimage] = useState(null)
  const [pathname, setpath] = useState('')
  const [title, settitle] = useState()
  const handleImageChange = (e) => {
    const file = e.target.files[0];
  	const formData = new FormData();
    formData.append("image", file);
    setimage(formData);
  };
  const handleSubmit = async (e) => {
    e.preventDefault()
    try {
      await axios.post('https://api.wesamelnagah.com/api/maincategory', {
        name,
        pathname,
        image,
        headers: {
          "Content-Type": "multipart/form-data",
        },
        // title
      })
      await axios.post('https://api.wesamelnagah.com/api/uplode',image, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
      setname('')
      setimage(null)
      setpath('')
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <div className="programs_container">
      <AppSidebar />
      <div className="wrapper d-flex flex-column min-vh-100">
        <AppHeader />
        <div className="body flex-grow-1">
          <CForm onSubmit={handleSubmit}>
            <div className="mb-3">
              <CFormLabel htmlFor="exampleFormControlInput1"> عنوان الباقة</CFormLabel>
              <CFormInput
                type="text"
                id="exampleFormControlInput1"
                onChange={(e) => setname(e.target.value)}
              />
              <CFormLabel htmlFor="exampleFormControlInput1"> مسار الباقة</CFormLabel>
              <CFormInput
                type="text"
                id="exampleFormControlInput1"
                onChange={(e) => setpath(e.target.value)}
              />
            </div>
            <div className="mb-3">
              <CFormLabel htmlFor="formFile">صورة الباقة</CFormLabel>
              <CFormInput type="file" id="formFile" onChange={handleImageChange} />
            </div>
            <div className="d-grid gap-2 col-6 mx-auto">
              <CButton color="primary" type="submit">
                Submit
              </CButton>
            </div>
          </CForm>
        </div>
        <AppFooter />
      </div>
    </div>
  )
}

هل يستطيع احد مساعدتي للقيام بذلك  

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

مرحبا , 

ليس من الجيد بشكل عام تخزين الصور في قاعدة البيانات في شكل buffer و ذلك لأسباب تتعلق بالperformance و الScalability,

ولكن بشكل عام فإذا كنت تستعمل node js فيمكنك فقط تخزين اسم التعريف لكل صورة 
مثلا تخزن اسم الصورة أنها image_1.png و عند الإستدعاء في الreact يقوم بوضع الurl الخاص بالbackend قبل التعريف 
مثلا : https://example.com/uploads/image_1.png
________

في حال ما إذا كنت تستعمل next js فأمر تخزين الصور يصبح أكثر تعقيدا خاصة في مراحل الproductions و في تلك الحالة يستحسن إستعمال aws 

مثال :
للتخزين :
 

const s3 = new S3Client({
  region: "me-south-1",
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
  },
});
//___________________________

import { PutObjectCommand } from "@aws-sdk/client-s3";
import generateUniqueId from "../date_id";

export default async function handleUploadFilesS3({
  buffer,
  filename,

}: {
  buffer: any;
  filename: string;
 
}) {
  try {
    let newFileName = `${generateUniqueId()}_${filename.replaceAll(
      " ",
      "_"
    )}`;
    let command = new PutObjectCommand({
      Bucket: process.env.AWS_S3_BUCKET_NAME as string,
      Key: newFileName,
      Body: buffer,
    });
    await s3.send(command);
    return { name: newFileName, ok: true };
  } catch (error) {
    console.log(error);
    return { error: error, ok: false };
  }
}

للإسترجاع :
 

 const games = await prisma.game.findMany();
  games.forEach(async (game) => {
    try {
      let command = new GetObjectCommand({
        Bucket: process.env.AWS_S3_BUCKET_NAME,
        Key: game.gameImg as string,
      });
      const url = await getSignedUrl(s3, command, { expiresIn: 3600 * 24 });
      game.gameImg = url;
    } catch (err) {
      console.log(err);
    }
  });

______
كمان يمكنك إستعمال طريقة الaws في المشاريع الخاصة بالnodejs أيضا .

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...