Skip to content

Commit 12cbb7c

Browse files
committed
update uploading method
1 parent 2cc646a commit 12cbb7c

File tree

15 files changed

+92
-33
lines changed

15 files changed

+92
-33
lines changed

.env

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@
44
ENV_VARIABLE=production_server_only_variable
55
NEXT_PUBLIC_ENV_VARIABLE=production_public_variable
66
DB_LOCAL_URL=mongodb://mongo:27017/denizpaz
7-
PORT=3000
7+
PORT=3000
8+
STORE_PATH=upload

.env.development

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33

44
DEVELOPMENT_ENV_VARIABLE="server_only_development_variable"
55
NEXT_PUBLIC_DEVELOPMENT_ENV_VARIABLE="public_development_variable"
6-
PORT=3000
6+
PORT=3000
7+
STORE_PATH=upload

.env.local.example

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
MONGODB_URI=
22
ENV_LOCAL_VARIABLE="server_only_variable_from_env_local"
33
NEXT_PUBLIC_ENV_LOCAL_VARIABLE="public_variable_from_env_local"
4-
PORT=3000
4+
PORT=3000
5+
STORE_PATH=upload

.env.production

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@
44
PRODUCTION_ENV_VARIABLE="server_only_production_variable"
55
NEXT_PUBLIC_PRODUCTION_ENV_VARIABLE="public_production_variable"
66
DB_LOCAL_URL=mongodb://mongo:27017/denizpaz
7-
PORT=3000
7+
PORT=3000
8+
STORE_PATH=upload

app/api/file/[name]/route.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { NextRequest, NextResponse } from "next/server";
2+
import { existsSync } from "fs";
3+
import fs from "fs/promises";
4+
import path from "path";
5+
import mime from "mime/lite";
6+
7+
export async function GET(
8+
req: NextRequest,
9+
{ params }: { params: { name: string } }
10+
) {
11+
const filePath = path.join(
12+
process.cwd(),
13+
process.env.STORE_PATH!,
14+
params.name
15+
);
16+
if (!existsSync(filePath)) {
17+
return NextResponse.json({ msg: "Not found" }, { status: 404 });
18+
}
19+
20+
const mimeType = mime.getType(filePath);
21+
const fileStat = await fs.stat(filePath);
22+
23+
const file = await fs.readFile(filePath);
24+
25+
const headers: [string, string][] = [
26+
["Content-Length", fileStat.size.toString()],
27+
];
28+
if (mimeType) {
29+
headers.push(["Content-Type", mimeType]);
30+
}
31+
return new NextResponse(file, {
32+
headers,
33+
});
34+
}

app/api/recipes/route.ts

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ import { stat, writeFile } from "fs/promises";
55
import { connectToDatabase } from "../../../lib/mongodb";
66
import { Recipe } from "../../../models";
77
import mime from 'mime';
8+
import { existsSync } from "fs";
9+
import fs from "fs/promises";
10+
import path from "path";
811

912
connectToDatabase();
1013

@@ -25,33 +28,36 @@ export async function GET() {
2528
export async function POST(req: Request) {
2629
const data = await req.formData();
2730
const file: File | null = data.get('photo') as unknown as File;
28-
const bytes = await file.arrayBuffer();
29-
30-
const buffer = Buffer.from(await file.arrayBuffer());
31-
const relativeUploadDir = `/uploads/recipes`;
32-
const uploadDir = join(process.cwd(), "public", relativeUploadDir);
33-
await stat(uploadDir);
34-
31+
32+
const fileArrayBuffer = await file.arrayBuffer();
33+
const destinationDirPath = path.join(process.cwd(), process.env.STORE_PATH!);
34+
35+
if (!existsSync(destinationDirPath)) {
36+
await fs.mkdir(destinationDirPath, { recursive: true });
37+
}
38+
39+
let name = data.get('name')
40+
var fileExtension = file.name.split('.').pop();
41+
let filename = `${name}.${fileExtension}`
42+
while (existsSync(path.join(destinationDirPath, filename))) {
43+
filename = `(1)` + filename;
44+
}
45+
await fs.writeFile(
46+
path.join(destinationDirPath, filename),
47+
Buffer.from(fileArrayBuffer)
48+
);
3549
try {
36-
const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
37-
const filename = `${file.name.replace(
38-
/\.[^/.]+$/,
39-
""
40-
)}-${uniqueSuffix}.${mime.getExtension(file.type)}`;
41-
await writeFile(`${uploadDir}/${filename}`, buffer);
42-
4350
const newRecipe = {
4451
name: data.get('name'),
4552
description: data.get('description'),
4653
ingredients: JSON.parse(data.get('ingredients') as string),
4754
steps: data.get('steps'),
48-
photo: `${relativeUploadDir}/${filename}`
55+
photo: `/api/file/${filename}`
4956
}
5057

51-
console.log("recipe", newRecipe)
5258
const recipe = new Recipe(newRecipe);
5359
const save = await recipe.save();
54-
return NextResponse.json({ status: 200, data: save });
60+
return NextResponse.json({ status: 200, data: save});
5561
} catch (error) {
5662
console.log(error);
5763
return NextResponse.json('error', {

app/api/revalidate/route.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { NextRequest, NextResponse } from 'next/server'
2+
import { revalidatePath } from 'next/cache'
3+
4+
export async function GET(request: NextRequest) {
5+
const path = request.nextUrl.searchParams.get('path') || '/'
6+
revalidatePath(path)
7+
return NextResponse.json({ revalidated: true, now: Date.now() })
8+
}

components/LatestRecipes.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ const LatestRecipes = ({ limitNumber }: LatestRecipesProps) => {
1919
GetAllRecipesResponse[] | undefined
2020
>(undefined);
2121
const [loading, setLoading] = useState(true);
22-
2322
// تابع get_all_recipes برای دریافت همه‌ی رسپی‌ها
2423
const get_all_recipes = async () => {
2524
setLoading(true);

components/RecipeCard.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import React from "react";
88
import Button from "./ui/Button";
99
import { Recipe } from "../types/Recipe";
1010
import { ArrowLeftIcon } from "@heroicons/react/24/solid";
11+
import path from "path";
1112

1213
// تعریف ویژگی‌های RecipeCardProps
1314
interface RecipeCardProps {
@@ -16,6 +17,7 @@ interface RecipeCardProps {
1617

1718
// تعریف کامپوننت RecipeCard
1819
const RecipeCard = ({ recipe }: RecipeCardProps) => {
20+
1921
return (
2022
<>
2123
<Link href={`recipes/${recipe?._id}`}>

develop.Dockerfile

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,24 @@
11
FROM node:18-alpine
22

3-
RUN mkdir -p /usr/src/app
3+
RUN mkdir -p /app
44

5-
WORKDIR /usr/src/app
5+
WORKDIR /app
66

7-
COPY package.json /usr/src/app/
7+
COPY package.json /app
88

99
RUN npm install -g next
1010

1111
RUN npm install
1212

13-
COPY . /usr/src/app
13+
COPY . /app
1414

15-
RUN npm run build
15+
RUN mkdir -p /app/.next/cache/images
16+
VOLUME /app/.next/cache/images
1617

17-
COPY --chown=10101 ./public /usr/src/app/public
18+
RUN npm run build
1819

1920
ENV DB_LOCAL_URL=mongodb://mongo:27017/denizpaz
2021

2122
EXPOSE 3000
2223

23-
CMD npm run launch
24+
CMD npm run start

0 commit comments

Comments
 (0)