You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hello devs. I recently uploaded my API to a VPS, and I'm having trouble recovering the images that are being saved locally. Whenever I try to open the image URL, I get a 404 Not Found error.
I'm not saving the images inside the API root, but in another folder on the VPS system (ubuntu) -
Path: ROOT dir/www/ibcb_arq/uploads/posts
When I save them in the project root in the path > ./upload < everything works, but I don't want to leave them in the root because every time I need to do a BUILD, everything will be erased.
`
import type { HttpContextContract } from "@IOC:Adonis/Core/HttpContext";
import Database from "@IOC:Adonis/Lucid/Database";
import Comentario from "App/Models/Comentario";
import Postagem from "App/Models/Postagem";
import User from "App/Models/User";
import { DateTime } from "luxon";
import Drive from "@IOC:Adonis/Core/Drive";
import { cuid } from "@IOC:Adonis/Core/Helpers";
import NotificationController from "./NotificationsController";
export default class PostagemsController {
public async postCreate({ response, request, auth }: HttpContextContract) {
try {
// Obtém o usuário autenticado
const userAuth = await auth.use("api").authenticate();
// Busca o usuário pelo ID
const user = await User.findByOrFail("id", userAuth.id);
if (!userAuth) {
return response.unauthorized({ message: "Usuário não autenticado." });
}
const allowedRoles = [1, 2, 3];
const hasAllowedRole = await Database.from("user_cargos")
.where("user_id", userAuth.id)
.whereIn("cargo_id", allowedRoles)
.first();
if (!hasAllowedRole) {
return response.unauthorized({
message: "Você não tem permissão para criar uma postagem.",
});
}
const conteudo = request.input("conteudo");
const imagem = request.file("imagem");
if (!conteudo && !imagem) {
return response.badRequest({
message: "É necessário fornecer pelo menos conteúdo ou imagem.",
});
}
let imageUrl: string | null = null;
if (imagem) {
// Salva a imagem no drive
const fileName = `${cuid()}.${imagem.extname}`;
await imagem.move("../ibcb_arq/uploads/postagens/", { name: fileName });
imageUrl = await Drive.getUrl(`./uploads/postagens/${fileName}`);
}
const postData = await Postagem.create({
user_id: user.id,
conteudo: conteudo || null, // Pode ser nulo se não foi fornecido conteúdo
imagem: imageUrl || null, // Pode ser nulo se não foi fornecida imagem
data_expiracao: DateTime.now().plus({ days: 60 }), // Define a data de expiração para 60 dias a partir de agora
});
const notificationController = new NotificationController();
await notificationController.sendNotificationToAllDevices(
"Nova Postagem",
"Uma nova postagem foi adicionada."
);
return response.created(postData);
} catch (error) {
// Tratamento de erro
if (error.code === "E_ROW_NOT_FOUND") {
return response.notFound({ message: "Usuário não encontrado." });
} else if (error.code === "E_VALIDATION_FAILURE") {
return response.unprocessableEntity({
message: "Dados de entrada inválidos.",
errors: error.messages,
});
}
return response.internalServerError({
message: "Ocorreu um erro ao processar a solicitação.",
});
}
}
`
config/drive.ts
`
import Env from "@IOC:Adonis/Core/Env";
import { driveConfig } from "@adonisjs/core/build/config";
import Application from "@IOC:Adonis/Core/Application";
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hello devs. I recently uploaded my API to a VPS, and I'm having trouble recovering the images that are being saved locally. Whenever I try to open the image URL, I get a 404 Not Found error.
I'm not saving the images inside the API root, but in another folder on the VPS system (ubuntu) -
Path: ROOT dir/www/ibcb_arq/uploads/posts
When I save them in the project root in the path > ./upload < everything works, but I don't want to leave them in the root because every time I need to do a BUILD, everything will be erased.
`
import type { HttpContextContract } from "@IOC:Adonis/Core/HttpContext";
import Database from "@IOC:Adonis/Lucid/Database";
import Comentario from "App/Models/Comentario";
import Postagem from "App/Models/Postagem";
import User from "App/Models/User";
import { DateTime } from "luxon";
import Drive from "@IOC:Adonis/Core/Drive";
import { cuid } from "@IOC:Adonis/Core/Helpers";
import NotificationController from "./NotificationsController";
export default class PostagemsController {
public async postCreate({ response, request, auth }: HttpContextContract) {
try {
// Obtém o usuário autenticado
const userAuth = await auth.use("api").authenticate();
// Busca o usuário pelo ID
const user = await User.findByOrFail("id", userAuth.id);
if (!userAuth) {
return response.unauthorized({ message: "Usuário não autenticado." });
}
}
`
config/drive.ts
`
import Env from "@IOC:Adonis/Core/Env";
import { driveConfig } from "@adonisjs/core/build/config";
import Application from "@IOC:Adonis/Core/Application";
export default driveConfig({
disk: Env.get("DRIVE_DISK"),
disks: {
Beta Was this translation helpful? Give feedback.
All reactions