Skip to content

Commit

Permalink
Sharp Image
Browse files Browse the repository at this point in the history
  • Loading branch information
FoundTheWOUT committed Mar 9, 2023
1 parent 461f4fc commit 00494b3
Show file tree
Hide file tree
Showing 5 changed files with 260 additions and 18 deletions.
6 changes: 6 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"command": "pnpm serve-dev",
"name": "Start server",
"request": "launch",
"type": "node-terminal"
},
{
"command": "pnpm web dev",
"name": "Run web dev",
Expand Down
2 changes: 2 additions & 0 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"morgan": "^1.10.0",
"multer": "1.4.5-lts.1",
"pg": "^8.9.0",
"sharp": "^0.31.3",
"typeorm": "^0.3.12",
"uuid": "^9.0.0"
},
Expand All @@ -27,6 +28,7 @@
"@types/cors": "^2.8.13",
"@types/express": "^4.17.17",
"@types/multer": "^1.4.7",
"@types/sharp": "^0.31.1",
"@types/uuid": "^9.0.1",
"nodemon": "^2.0.20"
}
Expand Down
58 changes: 41 additions & 17 deletions packages/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,41 +7,50 @@ import cors from "cors";
import OSS from "ali-oss";
import * as dotenv from "dotenv";
import { resolve } from "path";
import { rmSync } from "fs";
import { v4 as uuidv4 } from "uuid";
import { isProd } from "./const";
import { log } from "./utils";
import { auth } from "./middlerware/authentication";
import sharp from "sharp";

log("cwd:", process.cwd());
// dev load .env.dev, prod load .env
const dotenvPath = resolve(process.cwd(), isProd ? ".env" : ".env.dev");
dotenv.config({ path: dotenvPath });

const upload = multer({ dest: "uploads/" });
const upload = multer({ dest: "uploads/", storage: multer.memoryStorage() });

const ossPutAndRemoveLocal = async (
const ossPut = async (
client: OSS,
files: Express.Multer.File[]
files: Express.Multer.File[],
filenameFormatter?: (name: string) => string
) => {
try {
await Promise.all(
files.map((file) => {
return client.put(file.filename, resolve(file.path));
// return the Map<nanoid(from front_end),new_file_name(from multer)>
const entry = await Promise.all(
files.map(async (file) => {
const id = file.originalname;
const { name } = await client.put(
filenameFormatter ? filenameFormatter(id) : id,
file.buffer
);
return [id, name];
})
);
files.forEach((file) => {
rmSync(resolve(file.path));
});
return Object.fromEntries(
// return the Map<nanoid(from front_end),new_file_name(from multer)>
files.map((file) => [file.originalname, file.filename])
);
return Object.fromEntries(entry);
} catch (error) {
throw error;
}
};

const sharpImageToWebp = async (buf: Buffer) => {
const output = await sharp(buf)
.resize(200)
.webp({ lossless: true })
.toBuffer();
return output;
};

async function bootstrap() {
try {
const source = await createAppDataSource().initialize();
Expand Down Expand Up @@ -80,16 +89,30 @@ async function bootstrap() {
});

authRoute.post(
"/upload",
"/upload/image",
upload.array("file", 20),
async function (req, rep) {
if (!Array.isArray(req.files)) {
return rep.status(400).send("files is not array.");
}
try {
const fileMap = await ossPutAndRemoveLocal(ossClient, req.files);
// sharp image
const files: Express.Multer.File[] = await Promise.all(
req.files.map(async (file) => {
return {
...file,
buffer: await sharpImageToWebp(file.buffer),
} as Express.Multer.File;
})
);
const fileMap = await ossPut(
ossClient,
files,
(name) => `${name}.webp`
);
return rep.send(fileMap);
} catch (error) {
log(error);
return rep.status(500).send(error);
}
}
Expand All @@ -104,9 +127,10 @@ async function bootstrap() {
return rep.status(400).send("files is not array.");
}
try {
const fileMap = await ossPutAndRemoveLocal(ossClient, req.files);
const fileMap = await ossPut(ossClient, req.files);
return rep.send(fileMap);
} catch (error) {
log(error);
return rep.status(500).send(error);
}
}
Expand Down
4 changes: 3 additions & 1 deletion packages/web/src/app/music/add/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,13 @@ function AddMusic() {
// console.log("must file/cover");
// return;
// }

songs.append("file", new File([music.file], music.nanoId));
covers.append("file", new File([music.cover], music.nanoId));
}

try {
// return map of nanoid to file src
const [songFileMap, coverFileMap] = await Promise.all([
// song
fetch(`${process.env.NEXT_PUBLIC_API_GATE}/upload/song`, {
Expand All @@ -57,7 +59,7 @@ function AddMusic() {
throw new Error("reason");
}),
// cover
fetch(`${process.env.NEXT_PUBLIC_API_GATE}/upload`, {
fetch(`${process.env.NEXT_PUBLIC_API_GATE}/upload/image`, {
method: "POST",
headers: {
authorization: `Basic ${token}`,
Expand Down
Loading

1 comment on commit 00494b3

@vercel
Copy link

@vercel vercel bot commented on 00494b3 Mar 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.