change some files
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
// src/services/file.service.ts
|
||||
import axios from "axios";
|
||||
import FormData from "form-data";
|
||||
import { File } from "../../../models/File";
|
||||
require("dotenv").config();
|
||||
|
||||
interface UploadResult {
|
||||
id: string;
|
||||
url: string;
|
||||
size: number;
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
export const uploadFileToCDN = async (
|
||||
fileBuffer: Buffer,
|
||||
originalName: string,
|
||||
mimeType: string,
|
||||
): Promise<UploadResult> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", fileBuffer, {
|
||||
filename: originalName,
|
||||
contentType: mimeType,
|
||||
});
|
||||
|
||||
console.log(`Bearer ${process.env.CDN_SERVICE_TOKEN}`);
|
||||
// 1️⃣ ارسال به CDN
|
||||
const response = await axios.post(`http://localhost:3500/upload`, formData, {
|
||||
headers: {
|
||||
...formData.getHeaders(),
|
||||
Authorization: `Bearer ${process.env.CDN_SERVICE_TOKEN}`,
|
||||
},
|
||||
maxContentLength: Infinity,
|
||||
maxBodyLength: Infinity,
|
||||
});
|
||||
|
||||
console.log(response);
|
||||
|
||||
const { url, size, mime } = response.data;
|
||||
|
||||
// 2️⃣ ذخیره در دیتابیس
|
||||
const createdFile = await File.create({
|
||||
fileName: url.split("/").pop()!,
|
||||
originalName,
|
||||
mimeType: mime,
|
||||
|
||||
path: url,
|
||||
size,
|
||||
});
|
||||
|
||||
console.log(url);
|
||||
return {
|
||||
id: createdFile.id,
|
||||
url,
|
||||
|
||||
size,
|
||||
mimeType: mime,
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user