Add user image

Trackera year ago

Greetings, could someone help me where I'm going wrong when trying to add an image to the user like we have for devices. Thank you in advance. I implemented it this way in UserResource, MediaManager.

    @Path("{id}/image")
    @POST
    @Consumes("image/*")
    public Response uploadImage(
            @PathParam("id") String userId, File file,
            @HeaderParam(HttpHeaders.CONTENT_TYPE) String type) throws StorageException, IOException {

        User user = storage.getObject(User.class, new Request(
                new Columns.All(),
                new Condition.And(
                        new Condition.Equals("id", userId),
                        new Condition.Permission(User.class, getUserId(), User.class))));
        if (user != null) {
            String name = "user";
            String extension = type.substring("image/".length());
            try (var input = new FileInputStream(file);
                 var output = mediaManager.createUserFileStream(String.valueOf(user.getId()), name, extension)) {
                input.transferTo(output);
            }
            return Response.ok(name + "." + extension).build();
        }
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    private File createUserFile(String userName, String name) throws IOException {
        Path userFilePath = Paths.get(path, userName, name);
        Path directoryPath = userFilePath.getParent();
        if (directoryPath != null) {
            Files.createDirectories(directoryPath);
        }
        return userFilePath.toFile();
    }
    public OutputStream createUserFileStream(String id, String name, String extension) throws IOException {
        return new FileOutputStream(createUserFile(id, name + "." + extension));
    }
Trackera year ago

If anyone needs to create an image for the user, here is the way I achieved it.
Folders will be created in the /op/traccar/media directory for each user based on email
Add before

  private String generateUniqueFileName(String email, String extension) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = dateFormat.format(new Date());
        String random = UUID.randomUUID().toString().replaceAll("-", "");

        // Transforme o email em um formato adequado para nomes de arquivo, removendo caracteres especiais e espaços.
        String sanitizedEmail = email.replaceAll("[^a-zA-Z0-9]", "");

        return sanitizedEmail + "_" + timestamp + "_" + random + "." + extension;
    }
public UserResource() {
        super(User.class);
    }

Add to end of UserResources.java file

@Path("file/{email}/image")
    @POST
    @Consumes("image/*")
    public Response uploadImage(
            @PathParam("email") String email, File inputFile,
            @HeaderParam(HttpHeaders.CONTENT_TYPE) String type) throws IOException, StorageException {
       // permissionsService.checkAdmin(getUserId());

        // Verifique se o email do usuário é válido (você pode adicionar mais validações aqui).

        String root = config.getString(Keys.WEB_OVERRIDE, config.getString(Keys.MEDIA_PATH));
        var outputPath = Paths.get(root, email); // Use o email para criar um diretório específico para cada usuário.
        Files.createDirectories(outputPath);

        String extension = type.substring("image/".length());

        // Gere um nome de arquivo exclusivo, se necessário.
        String fileName = generateUniqueFileName(email, extension);

        try (
                var input = new FileInputStream(inputFile);
                var output = new FileOutputStream(outputPath.resolve(fileName).toFile())) {
            input.transferTo(output);
        }
        return Response.ok(fileName).build();
    }
You k9 months ago

Hello
Does it works ? have you managed to add an image for users? Please share a screen as an example

Youssef6 months ago

Hi,
does anyone resolve this? I need to add image to each user account as avatar but I am stuck. I can see some guy in youtube has add it as accordion field in user setting but does not want to share the solution with me.

uplink6 months ago

I have already implemented this you can check under edit user

[redacted]

Youssef6 months ago

Hi Uplink, can you guide me on how you do that. Thanks.